Server-Side Application and Data Management IT IS 3105 (Spring 2010) Lecture 7 PHP Strings and Arrays
Backdrop Data Retrieve a lot Need tools to manipulate the data Various sources E.g. Relational databases Single query could return: no data 1 datum or 1 row of data huge amount complex data Need tools to manipulate the data Reading complex data Formatting complex responses
Strings A quick review
String Functions addcslashes addslashes bin2hex chop chr chunk_split convert_cyr_string convert_uudecode convert_uuencode count_chars crc32 crypt echo explode fprintf get_html_translation_table hebrev hebrevc html_entity_decode htmlentities htmlspecialchars_decode htmlspecialchars implode join lcfirst levenshtein localeconv ltrim md5_file md5 metaphone money_format nl_langinfo nl2br number_format ord parse_str print printf quoted_printable_decode quoted_printable_encode quotemeta rtrim setlocale sha1_file similar_text soundex sprintf sscanf str_getcsv str_ireplace str_pad str_repeat str_replace str_rot13 str_shuffle str_split str_word_count strcasecmp strchr strcmp strcoll strcspn strip_tags stripcslashes stripos stripslashes stristr strlen strnatcasecmp strnatcmp strncasecmp strncmp strpbrk strpos strrchr strrev strripos strrpos strspn strstr strtok strtolower strtoupper strtr substr_compare substr_count substr_replace substr trim ucfirst ucwords vfprintf vprintf vsprintf wordwrap
String Functions addcslashes addslashes bin2hex chop chr chunk_split Quote string with slashes in a C style addslashes Quote string with slashes bin2hex Convert binary data into hexadecimal representation chop Alias of rtrim chr Return a specific character chunk_split Split a string into smaller chunks convert_cyr_string Convert from one Cyrillic character set to another convert_uudecode Decode a uuencoded string convert_uuencode Uuencode a string count_chars Return information about characters used in a string crc32 Calculates the crc32 polynomial of a string crypt One-way string encryption (hashing) echo Output one or more strings explode Split a string by string fprintf Write a formatted string to a stream get_html_translation_table Returns the translation table used by htmlspecialchars and htmlentities hebrev Convert logical Hebrew text to visual text hebrevc Convert logical Hebrew text to visual text with newline conversion html_entity_decode Convert all HTML entities to their applicable characters htmlentities Convert all applicable characters to HTML entities
String Functions htmlspecialchars_decode metaphone Convert special HTML entities back to characters htmlspecialchars Convert special characters to HTML entities implode Join array elements with a string join Alias of implode lcfirst Make a string's first character lowercase levenshtein Calculate Levenshtein distance between two strings localeconv Get numeric formatting information ltrim Strip whitespace (or other characters) from the beginning of a string md5_file Calculates the md5 hash of a given file md5 Calculate the md5 hash of a string metaphone Calculate the metaphone key of a string money_format Formats a number as a currency string nl_langinfo Query language and locale information nl2br Inserts HTML line breaks before all newlines in a string number_format Format a number with grouped thousands ord Return ASCII value of character parse_str Parses the string into variables print Output a string printf Output a formatted string quoted_printable_decode Convert a quoted-printable string to an 8 bit string
String Functions quoted_printable_encode quotemeta rtrim setlocale Convert a 8 bit string to a quoted-printable string quotemeta Quote meta characters rtrim Strip whitespace (or other characters) from the end of a string setlocale Set locale information sha1_file Calculate the sha1 hash of a file sha1 Calculate the sha1 hash of a string similar_text Calculate the similarity between two strings soundex Calculate the soundex key of a string sprintf Return a formatted string sscanf Parses input from a string according to a format str_getcsv Parse a CSV string into an array str_ireplace Case-insensitive version of str_replace. str_pad Pad a string to a certain length with another string str_repeat Repeat a string str_replace Replace all occurrences of the search string with the replacement string str_rot13 Perform the rot13 transform on a string str_shuffle Randomly shuffles a string str_split Convert a string to an array str_word_count Return information about words used in a string strcasecmp Binary safe case-insensitive string comparison strchr Alias of strstr
String Functions strcmp strcoll strcspn strip_tags stripcslashes Binary safe string comparison strcoll Locale based string comparison strcspn Find length of initial segment not matching mask strip_tags Strip HTML and PHP tags from a string stripcslashes Un-quote string quoted with addcslashes stripos Find position of first occurrence of a case- insensitive string stripslashes Un-quotes a quoted string stristr Case-insensitive strstr strlen Get string length strnatcasecmp Case insensitive string comparisons using a "natural order" algorithm strnatcmp String comparisons using a "natural order" algorithm strncasecmp Binary safe case-insensitive string comparison of the first n characters strncmp Binary safe string comparison of the first n characters strpbrk Search a string for any of a set of characters strpos Find position of first occurrence of a string strrchr Find the last occurrence of a character in a string strrev Reverse a string strripos Find position of last occurrence of a case- insensitive string in a string strrpos Find position of last occurrence of a char in a string strspn Finds the length of the first segment of a string consisting entirely of characters contained within a given mask.
String Functions strtok vfprintf strtolower Tokenize string strtolower Make a string lowercase strtoupper Make a string uppercase strtr Translate certain characters substr_compare Binary safe comparison of 2 strings from an offset, up to length characters substr_count Count the number of substring occurrences substr_replace Replace text within a portion of a string substr Return part of a string trim Strip whitespace (or other characters) from the beginning and end of a string ucfirst Make a string's first character uppercase ucwords — Uppercase the first character of each word in a string vfprintf Write a formatted string to a stream vprintf Output a formatted string vsprintf Return a formatted string wordwrap Wraps a string to a given number of characters
Most used/useful
Print echo() printf() sprintf() Send data to stdout Send formatted data to stdout sprintf() Send formatted data to a string variable
Substring substr() Returns a substring from the string
Trim Remove unwanted whitespace from strings all before and after the string ltrim() all before the string rtrim() all after the string PHP whitespace characters: " " (ASCII 32 (0x20)), an ordinary space "\t" (ASCII 9 (0x09)), a tab "\n" (ASCII 10 (0x0A)), a new line (line feed) "\r" (ASCII 13 (0x0D)), a carriage return "\0" (ASCII 0 (0x00)), the NUL-byte "\x0B" (ASCII 11 (0x0B)), a vertical tab
Manipulation strtoupper() strtolower() ucfirst() ucwords() strrev() set all characters upper case strtolower() set all characters lower case ucfirst() set first character to upper case ucwords() set the first character in each word to upper case strrev() reverse the string
Misc strlen() strstr() returns string length returns the location of a string in a string
String – Numeric Conversions Number String Casting – (string) $myNum = 3.14159; echo (string) $myNum, “\n”; Functions – strval() echo strval($myNum), “\n”; Formating - sprintf() $isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
String – Numeric Conversions String Number Integer Must only contain digits and optionally a sign (+ or -) Float Must only contain digits, sign, and/or “.”, “e”, or “E” Casting – (float) and (int) (float) Cast to a floating point number (int) Cast to an integer Automatic Ex: $astring = “1.24”; $value = 5 + $astring;
Type Juggling Watch out for conventions which are context based Base rule: If the string starts with numerics it uses them and discards the rest If the string starts with alphabetics it use the value 0 Examples: <?php $foo = "0"; // $foo is string (ASCII 48) $foo += 2; // $foo is now an integer (2) $foo = $foo + 1.3; // $foo is now a float (3.3) $foo = 5 + "10 Little Piggies"; // $foo is integer (15) $foo = 5 + "10 Small Pigs"; // $foo is integer (15) ?> <?php $foo = 1 + "10.5"; // $foo is float (11.5) $foo = 1 + "-1.3e3"; // $foo is float (-1299) $foo = 1 + "bob-1.3e3"; // $foo is integer (1) $foo = 1 + "bob3"; // $foo is integer (1) $foo = 1 + "10 Small Pigs"; // $foo is integer (11) $foo = 4 + "10.2 Little Piggies"; // $foo is float (14.2) $foo = "10.0 pigs " + 1; // $foo is float (11) $foo = "10.0 pigs " + 1.0; // $foo is float (11) ?>
Arrays
Arrays Collection of values stored in a single name Use an index or a key to retrieve values
Array Functions array_change_key_case array_chunk array_combine array_count_values array_diff_assoc array_diff_key array_diff_uassoc array_diff_ukey array_diff array_fill_keys array_fill array_filter array_flip array_intersect_assoc array_intersect_key array_intersect_uassoc array_intersect_ukey array_intersect array_key_exists array_keys array_map array_merge_recursive array_merge array_multisort array_pad array_pop array_product array_push array_rand array_reduce array_replace_recursive array_replace array_reverse array_search array_shift array_slice array_splice array_sum array_udiff_assoc array_udiff_uassoc array_udiff array_uintersect_assoc array_uintersect_uassoc array_uintersect array_unique array_unshift array_values array_walk_recursive array_walk array arsort asort compact count current each end extract in_array key krsort ksort list natcasesort natsort next pos prev range reset rsort shuffle sizeof sort uasort uksort usort
Array Functions array_fill array_change_key_case Changes all keys in an array array_chunk Split an array into chunks array_combine Creates an array by using one array for keys and another for its values array_count_values Counts all the values of an array array_diff_assoc Computes the difference of arrays with additional index check array_diff_key Computes the difference of arrays using keys for comparison array_diff_uassoc Computes the difference of arrays with additional index check which is performed by a user supplied callback function array_diff_ukey Computes the difference of arrays using a callback function on the keys for comparison array_diff Computes the difference of arrays array_fill_keys Fill an array with values, specifying keys array_fill Fill an array with values array_filter Filters elements of an array using a callback function array_flip Exchanges all keys with their associated values in an array array_intersect_assoc Computes the intersection of arrays with additional index check array_intersect_key Computes the intersection of arrays using keys for comparison array_intersect_uassoc Computes the intersection of arrays with additional index check, compares indexes by a callback function array_intersect_ukey Computes the intersection of arrays using a callback function on the keys for comparison array_intersect Computes the intersection of arrays array_key_exists Checks if the given key or index exists in the array array_keys Return all the keys of an array
Array Functions array_map array_merge_recursive array_merge Applies the callback to the elements of the given arrays array_merge_recursive Merge two or more arrays recursively array_merge Merge one or more arrays array_multisort Sort multiple or multi-dimensional arrays array_pad Pad array to the specified length with a value array_pop Pop the element off the end of array array_product Calculate the product of values in an array array_push Push one or more elements onto the end of array array_rand Pick one or more random entries out of an array array_reduce Iteratively reduce the array to a single value using a callback function array_replace_recursive Replaces elements from passed arrays into the first array recursively array_replace Replaces elements from passed arrays into the first array array_reverse Return an array with elements in reverse order array_search Searches the array for a given value and returns the corresponding key if successful array_shift Shift an element off the beginning of array array_slice Extract a slice of the array array_splice Remove a portion of the array and replace it with something else array_sum Calculate the sum of values in an array array_udiff_assoc Computes the difference of arrays with additional index check, compares data by a callback function array_udiff_uassoc Computes the difference of arrays with additional index check, compares data and indexes by a callback function
Array Functions array_udiff array_uintersect_assoc Computes the difference of arrays by using a callback function for data comparison array_uintersect_assoc Computes the intersection of arrays with additional index check, compares data by a callback function array_uintersect_uassoc Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions array_uintersect Computes the intersection of arrays, compares data by a callback function array_unique Removes duplicate values from an array array_unshift Prepend one or more elements to the beginning of an array array_values Return all the values of an array array_walk_recursive Apply a user function recursively to every member of an array array_walk Apply a user function to every member of an array array Create an array arsort Sort an array in reverse order and maintain index association asort Sort an array and maintain index association compact Create array containing variables and their values count Count all elements in an array, or properties in an object current Return the current element in an array each Return the current key and value pair from an array and advance the array cursor end Set the internal pointer of an array to its last element extract Import variables into the current symbol table from an array in_array Checks if a value exists in an array key Fetch a key from an array
Array Functions krsort reset Sort an array by key in reverse order ksort Sort an array by key list Assign variables as if they were an array natcasesort Sort an array using a case insensitive "natural order" algorithm natsort Sort an array using a "natural order" algorithm next Advance the internal array pointer of an array pos Alias of current prev Rewind the internal array pointer range Create an array containing a range of elements reset Set the internal pointer of an array to its first element rsort Sort an array in reverse order shuffle Shuffle an array sizeof Alias of count sort Sort an array uasort Sort an array with a user-defined comparison function and maintain index association uksort Sort an array by keys using a user- defined comparison function usort Sort an array by values using a user- defined comparison function
Array Functions Creating
Creating an Array Informally Formally Traditional method Use: $testGrade[1] = 85; Use: echo “Your grade “, $testGrade[1]; Add more values $testGrade[2] = 92; $testGrade[3] = 88; Formally $testGrade = array(85, 92, 88);
Arrays with string indexes Informally $ages[“Bob”] = 25; $ages[“Mary”] = 32; $ages[“Fido”] = 7;
Array Functions
count Returns the number of elements in the array count($myArray)
array copy Easy to copy one array to another $myArray2 = $myArray1;
Removing elements Setting an array element to null (“”) does not remove it unset() unset($myArray1[2]); Will remove the 3rd element from myArray1
Looping through arrays foreach() Will start with the 1st element in the array Each iteration (loop) through the array will access the next element Loop ends after the last element is accessed
Sorting sort() rsort() asort() ksort() krsort() rearrange the elements in an array ascending order rsort() descending order asort() If original array has text key they are normally replaced by numeric indices use asort() to retain the text keys note: the text key is kept with the value, the order of the elements is changed ksort() Sort on the key values krsort() Reverse sort on the key values
Array Navigation Use the array pointer to navigate: current() next() returns the current array element next() move to the next array element and return it prev() move to the previous array element and return it reset() set the pointer to the beginning of the array
implode() and explode() turn an array into a character string implode($pString, $myArray1); Where $pString has the value to separate the array elements in the end string Typically a “,” explode turns a string into an array explode($pString, $myArray2); Uses $pString as the parsing token for the array elements
Resume 2/4
extract() and compact() Use with string indexed arrays Creates a variables with string indexes Assigns the value of the index with that variable compact() Creates an array with the variables names as the string indexes
Merging and Splitting array_slice() array_merge() array array_slice ( array array, int offset [, int length]) if offset is neg, count from end if length is neg, stop that many elements from the end <?php $input = array("a", "b", "c", "d", "e"); $output = array_slice($input, 2); // returns "c", "d", and "e" $output = array_slice($input, 2, -1); // returns "c", "d" $output = array_slice($input, -2, 1); // returns "d" $output = array_slice($input, 0, 3); // returns "a", "b", and "c" ?> array_merge() array array_merge ( array array1 [, array array2 [, array ...]]) <?php $array1 = array("color" => "red", 2, 4); $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4); $result = array_merge($array1, $array2); print_r($result); ?>
Comparing Arrays array_diff() array_intersect() array_diff_assoc() Create a new array with elements that are different $arr1 = (1, 2, 3); $arr2 = (3, 4, 5); $diff = array_diff($arr1, $arr2); $diff will contain 1 and 2 The elements in $arr1 that are not in $arr2 array_intersect() Create a new array with the elements that are common $arr1 = (1, 2, 3); $arr2 = (3, 4, 5); $same = array_intersect($arr1, $arr2); $diff will contain 3 The elements in $arr1 and in $arr2 array_diff_assoc() array_intersect_assoc() Works if the keys or values are different or the same respectively
Manipulating Arrays Delete duplicates Add elements of array array_unique() Add elements of array array_sum() $scores = (20, 15, 17, 20, 18); $numScores = count($scores); $total = array_sum($scores); $average = $total/$numScores; Flipping an array – exchange arrays keys and values array_flip()
Multidimensional Arrays Strictly speaking arrays are single dimensional in PHP Use arrays of arrays to create multidimensional arrays $children[“Zedd”][1] = “Richard”; $children[“Zedd”][2] = “Mary”; $children[“Shota”][1] = “Kahlan”; $children[“Zedd”][3] = “Rachel”; $children[“Shota”][2] = “Denna”;
Array Operators + == === != <> !== Union of 2 arrays TRUE if arrays have the same elements === TRUE if arrays have same elements in the same order != TRUE if arrays not equal <> Same as != !== TRUE if arrays are not identical