Arrays – PHP Certification Exam Series [4]


PHP Array - PHP Certification Exam

Introduction: This is the fourth part of my study notes for the Zend PHP Certification Exam. You can read more about my PHP Certification exam journey here.

Article Highlights

Array Basics

  • Array is a way of ordering data by associating values to keys
  • Indexed arrays (enumerative arrays): numeric keys, either auto assigned (1 larger than the all-time largest index of the array) or assigned manually
  • Associative arrays: keys composed of alphanumerics
  • arrays can be nested to form multi-dimensional arrays
  • keys containing only digits (including floats) are cast to integers (discarding any decimals)
  • array keys are case-sensitives, but type-insensitive
  • use print_r($array) or var_dump($array) or var_export($array) to display the array in a readable format, var_export($array) will print/return the $array in valid PHP code
  • is_array($array) to check for array
  • array_key_exists($key, $array) to check of existence of a key value (or an array of keys)
  • in_array($value, $array, $strict==false) to check for existence of a value (or an array of values), use in_array instead of isset()
  • array_search($value,$array) to return the key of the $value if exists, FALSE if not found
  • array_keys($array, $value(optional), $strict==false) to extract all/matched keys in an array
  • array_values($array) to extract all values in an array, keys NOT preserved
  • count($array) [same as sizeof($array)] to return the number of elements within the array, note count(abc) return 1
  • unset($array[0]) or unset($array) to remove array element/array
$array = array(1,2,3);
print_r($array);    // Array ( [0] => 1 [1] => 2 [2] => 3 )
var_dump($array);   // array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
var_export($array); // array ( 0 => 1, 1 => 2, 2 => 3, )

 

Creating Arrays

  • $array = [‘a’,’b’]; or $array[]=’a’; $array[]=’b’;
  • $array = array( ‘a’=>’b’ , ‘c’ , 3=>’d’, ); // the presence of a final comma is legal in array definition
  • $array = range( 1.2 , 6.1 , 2 );  // == array(1.2, 3.2, 5.2)  create an array within the range with increment 2
  • $array = range(‘a’,’z’);  // == array(‘a’,’b’,…’z’) create an array within the range of characters
  • $array = array_fill(0,3,’hello’);  // == array(0=>’hello’,1=>’hello’,…3=>’hello’)
  • $keys = array(‘a’,1,0,’b’); $array = array_fill_keys($keys,’hello’);   // == array(‘a’=>’hello’,0=>’hello’,…’b’=>’hello’)
  • $array = array_pad($array,total_length,$value);  // copy and extend the $array to the defined length with $value
  • $array = explode($delimiter, $string);  // create an array by returning the parts of the $string as values delimited by the $delimiter. e.g. $array = explode(‘ ‘,’a b c’); // $array = array(‘a’,’b’,’c’);
  • $string = implode($delimiter, $array); $string = join($delimiter, $array);  // create a string from the $array with the $delimiter added in-between values
  • $input = array( “1”=>”A”,1=>”B”,“C”,2=>”D”);echo count($input); // answer 2
  • $array = str_split(“ABCDZ”,1); // == array(‘A’,’B’,’C’,’D’,’Z’);

Comparing Arrays

  • $array1==$array2   // if all key/value pairs are the same, irrespective of the order 
  • $array1===$array2   // if all key/value pairs and order of values are the same
  • array_diff($array1, $array2)  // Returns an array containing all the entries from array1 that are not present in any of the other arrays, array key is NOT preserved
  • array_udiff($array1, $array2, callback function)
  • array_diff_assoc($array1, $array2) // Unlike array_diff() the array keys are also used in the comparison.
  • array_diff_uassoc($array1, $array2, callback function)
  • array_udiff_assoc($array1, $array2) // Unlike array_udiff() the array keys are also used in the comparison.
  • array_udiff_uassoc($array1, $array2, callback function1, callback function2)
  • array_diff_key($array1, $array2)  // Returns an array containing all the keys and values from array1 that the key values are not present in any of the other arrays
  • array_diff_ukey($array1, $array2, callback function)
  • array_interset($array1, $array2)  // returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
  • array_uinterest($array1, $array2, callback function)
  • array_intersect_assoc($array1, $array2) //  keys are also used in the comparison, note that for numerical indexes, both must also be the same for the comparison
  • array_intersect_uassoc($array1, $array2, callback function)
  • array_uintersect_assoc($array1, $array2, callback function)
  • array_uintersect_uassoc($array1, $array2, callback function1, callback function2)

Iteration

  • foreach($array AS $key=>$value){ … } – the internal pointer is reset before the execution
  • foreach($array AS &$value) { … } – pass by reference, the original $array is altered. remember to unset $value after the loop, otherwise unexpected changes to the $array will result afterwards as $value is now a reference to the array element
  • while(list($a,$b,$c)=$array) { … } – assign values to $a,$b,$c in turn till end of $array
  • end() – move pointer to last element
  • key() – retreives key from current position, return NULL if past the last element
  • current() – [same as pos( )retrieves value from current position, return FALSE if not a value is present
  • next() – advances array pointer one spot then returns current value
  • prev() – rewinds the array pointer one spot, then returns the current value
  • reset() – resets the array pointer to the beginning of the array
while (key ($array) !== null) {  // != is incorrect as key may be 0
echo key($array) .": " .current($array) . PHP_EOL;
next($array);
}
  • each() – (internal pointer NOT reset before execution) returns the current key and value from the array, then iterates till the end, the key/value pair is returned in a four-element array, with the keys 0, 1, key, and value. each() is typically used in conjunction with list() to traverse an array as assigning the array to another variable will reset the internal pointer, causing an infinite loop
  • the function array_walk($array, func()) array_walk_recursive($array, func())will subject all elements to a callback function, recursive will operate on the arrays within the array as well (the key for the array element will be ignored)
  • the function array_filter($array, func())will subject all elements to a callback function, if the func() returns true, the key/value pair will be included in the new output array

Re-ordering and Sorting

  • array_flip()-  invert the key/value relationship, i.e. key becomes value and value becomes key
  • array_reverse()-  reverse the order of elements, i.e. last becomes first
  • bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) – sorts values alphabetically, key values (even associative) are not preserved. For multidimensional arrays, or sorting more than 1 arrays at a time, use array_multisort( )
    • SORT_LOCALE_STRING – sorts as strings according to locale setting
    • SORT_REGULAR – normal sorting
    • SORT_NUMERIC- numeric sorting
    • SORT_STRING- sorts as strings
  • rsort()-  reverse sorts values alphabetically, key values (even associative) are not preserved
  • ksort()- sorts by keys, key associations maintained
  • asort()- maintains key associations
  • arsort()- maintains key associations, sorts in reverse
  • usort($array, “callback”)| ursort() | uksort()- user-defined sort, with a callback, key values (even associative) are not preserved for usort, but preserved for others
  • bool natsort ( array &$array ) | natcasesort ()- use natural sort, key associations maintained
  • array array_rand (array $array, int number_of_elements)-  return randomly a defined number of keys from the array
  • bool shuffle ( array &$array )- reorder in a random order, key values (even associative) are NOT preserved

Stacks & Queues – original array is changed

  • Stack, implementing LIFO (last in, first out)
  • int array_push ( array &$array , mixed $var [, mixed $… ] ) – add element(s) to the end and return the number of array elements, e.g. $n = array_push ($array, 4, 5);  // $n == total number of elements
  • mixed array_pop ( array &$array ) – remove and return the last element from the array
  • Queue, implementing FIFO (fist in, first out)
  • int array_unshift ( array &$array , mixed $var [, mixed $… ] ) – add element(s) to the beginning and return the number of array elements, e.g. $n = array_unshift ($array, 4, 5);  // $n == total number of elements
  • mixed array_shift ( array &$array ) – remove and return the first element from the array

Array Functions

array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )
– return the sliced array, the original array is untouched
– $offset element is counted from 0
– if $length is omitted, will contain elements till the end
– negative $offset means element position counted from the end (not including this one)
– if $preserve_keys == TRUE, numeric keys will be preserved, associative keys will always be preserved

array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement ]] )
– cut out a chunk of an array and replace with new elements (if supplied) and return the extracted values
– $offset element is included
– negative $offset means element position counted from the end (not including this one)

$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
// $input is now array("red", "green")

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
// $input is now array("red", "green", "blue", "black", "maroon")

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green", "blue", "purple", "yellow");

array_merge ( array $array1 , array $array2, … )
– associative key values preserved; numeric key values renumbered
– If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
– note: $array1 + $array2 The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key’s element from the second array will be ignored.

array_merge_recursive ( array $array1 , array $array2, … )
– If the input arrays have the same string keys, then the values for these keys are merged together into an array
– If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

array_map ( callable func() name[‘strtoupper’] , array $array1, array $array2, … )
– the callback function should contain the same number of arguments as the number of arrays
– return an array with all values return by the callback function
– if the callback is NULL, the arrays will be combined with $array[0][0]=$array1[0], $array[0][1]=$array2[0] and so on
– keys not preserved

array_replace ( array $array1 , array $array2, … )
– replace or add key/value pairs to $array1, the same keys will overwrite the value, while different keys will be added

array_replace_recursive ( array $array1 , array $array2, … )
– array_replace recursively

array_combine ( array $keys , array $values )
– create a new array, first array becomes keys, second array becomes values
– FALSE if number of elements in $keys and $values are not equal

array_unique ( array $array1 , $sort_flags )
– compare the values, only the first unique value together with its key will be shown, by default, 4 “4” are considered the same

array_change_key_case($input_array, CASE_UPPER|CASE_LOWER)
– copy and return the $input_array with the case of all keys changed

array_count_values($array)
– copy and return an associative array with all the values of $array as keys and counts of the values as value

array_reduce ( array $array, callable func(), $initial_value )
– reduce the array to a single value based on the callback function

array_sum ( array $array )
– return the sum of the values in an array (with type casted to float)

array_product ( array $array )
– return the product of the values in an array (with type casted to float)

compact ( varname, varname, … )
– creates an array containing variables and their values
– opposite of extract

extract ( array &$var_array [, int $extract_type = EXTR_OVERWRITE [, string $prefix = NULL ]])
– turn all key/value pairs of an associative array into variables with the values assigned
– e.g. $arr = array(“a”=>”b”); extract($arr); // result: $a=b

SPL, Objects as arrays

  • stdClass – stdClass is Predefined Classes since PHP 5. It is available class provided by PHP to create an object and assign key/value pairs to it (e.g. in to cast object to an array internally). $object = new StdClass; $object->foo = ‘bar’;
  • arrayObject – allows objects to function as arrays, provided by SPL (Standard PHP Library)
  • new ArrayObject($var); // $var can either be array or object (only public properties)
  • $arrayobj = new ArrayObject($array,ArrayObject::STD_PROP_LIST); Properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.). To access the properties, use $arrayobj->prop instead of $arrayobj[‘prop’]
  • $arrayobj = new ArrayObject($array,ArrayObject::ARRAY_AS_PROPS);  Entries can be accessed as properties (read and write), both $arrayobj->prop and $arrayobj[‘prop’] are valid
  • $arrayobj = new ArrayObject(array(‘first’,’second’,’third’));$arrayobj->append(‘fourth’);
  • $arrayobj->asort(‘fourth’);
  • $arrayobj->getArrayCopy(); //export as array
  • $arrayobj->setFlags(ArrayObject::ARRAY_AS_PROPS);
  • $arrayobj->getFlags();
  • $iterator=$arrayobj->getIterator(); while($iterator->valid()){echo $iterator->key();$iterator->next();} //to perform iteration
  • $arrayobj->setIteratorClass(‘MyArrayIterator’); //check for existence of a key
  • $arrayobj->getIteratorClass();
  • $arrayobj->offsetExists(‘key’); //check for existence of a key
  • $arrayobj->offsetGet(‘key’); //get the value for a key
  • $arrayobj->offsetSet(‘key’,’value’); //set a new key/value pair
  • $arrayobj->offsetUnset(‘key’);
  • $arrayobj->serialize(); //serialize the values
  • $arrayobj->unserialize();

 

 

You can read more about my PHP Certification exam journey here.

Support website running for FREE, thanks!

If you find this post helpful and if you are thinking of buying from Amazon, please support the running cost of this website at no extra cost to you by searching and buying through the search box below. Thank you very much for your help!

Edward Chung

Edward Chung aspires to become a full-stack web developer and project manager. In the quest to become a more competent professional, Edward studied for and passed the PMP Certification, ITIL v3 Foundation Certification, PMI-ACP Certification and Zend PHP Certification. Edward shares his certification experience and resources here in the hope of helping others who are pursuing these certification exams to achieve exam success.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

2 Responses

  1. Alex says:

    Hi Edward! I found the mistake:
    Now: array_search($array, $value) to return the key of the $value if exists, FALSE if not found
    Should be: array_search($value, $array) to return the key of the $value if exists, FALSE if not found
    http://php.net/manual/en/function.array-search.php