Introduction to PHP for Os X by Example

Arrays

  • Arrays are list of strings, numbers and/or arrays.
  • A basic numeric array (one that has numeric indices) is created using the following syntax: $array_name = array('var1','var2','var3',4,5);
  • Array names follow the same rules as variable names.
  • Array names and variable names come from the same pool so you can’t have an array and a variable with the same name.
  • You can also create an array using the big arrow syntax, =>, which can make arrays more readable. Especially associative arrays.
  • Associative arrays have string keys instead of numeric.
  • Printing an array just using syntax like this, print($array_name) will only print out the word ‘Array’ (the variable type).
  • We can use printr() to print out an entire array so that we can see its structure. This is very useful when debugging.
  • Use implode(string glue, array pieces) to convert an array into a string with a specific string as a delimiter.
  • The count() function is used to find the length of an array.
  • We can remove the last item from an array and assign it to a variable using the array_pop() function and we can add an element to the end of an array using .
  • The functions array_shift() and array_unshift perform the same task as array_pop() and array_push() only they act on the front of the array.
  • Use this syntax to add an additional elements to a numeric: $array_name[] = 'New Element';
  • Numeric indices (of numeric arrays) can be used to access array elements so we can print them or assign them to variables etc.: $var_name = $array_name[0];
  • Associative array elements can be accessed using there key names: $var_name = $array_name['Key Name'];
  • Conversely $array_name[0] = "val"; $array_name['Key Name'] = "val";
  • The foreach control structure is used to loop through an array.
  • We can use the sort() function to sort an array and the rsort() function to sort in reverse.
  • Using implode on an associative array will only implode the arrays values and not the keys.
  • Use assort to sort associative arrays (arsort for reverse sort) – this will sort the array by its values. On the other hand ksort (krsort for the reverse) will sort it by its keys.
  • To get an array of the keys form an associative array use array_keys() and array_values() to get an array of the values.
  • To check and see if a specific key exists in an array we use the array_key_exists() function.
  • To delete an element from an array completely (both its key/index and value) use unset().

Resources