Working with Arrays

ARRAYS ARE, PERHAPS, THE most powerful aspect of PHP. The degree of freedom that the language allows a developer when creating and manipulating arrays is nothing short of spectacular: not only can you mix-and-match different types of keys and values, but you can perform all sorts of operations on them, from sorting to splitting to combining. With great powers, however, come great responsibilities. The flip side of such a vast array of possibilities (no pun intended) is that knowing the best way to manipulate arrays is not always an easy task. This portion of the exam focuses on your ability to understand how arrays work, not only from a theoretical viewpoint, but also from a practical one. Therefore, expect a lot of questions in which you’ll find yourself facing a brief script, asked to understand what’s wrong with it or what its final result will be.

15 cards   |   Total Attempts: 182
  

Cards In This Set

Front Back
Array values are keyed by ______ values (called indexed arrays) or using ______ values (called associative arrays). Of course, these key methods can be combined as well. A. Float, string B. Positive number, negative number C. Even number, string D. String, Boolean E. Integer, string
Arrays that are keyed by integer values are called indexed arrays, while those keyed by strings are called associative arrays. The correct answer is, therefore, E.
Consider the following array, called $multi_array. How would the value cat be referenced within the $multi_array array? <?php $multi_array = array("red", "green", 42 => "blue", "yellow" => array("apple", 9 => "pear", "banana", "orange" => array("dog", "cat", "iguana") ) ); ?> A. $multi_array['yellow']['apple'][0] B. $multi_array['blue'][0]['orange'][1] C. $multi_array[3][3][2] D. $multi_array['yellow']['orange']['cat'] E. $multi_array['yellow']['orange'][1]
The value cat is in an array buried within two other arrays. Following the path to the string, we see that, first, the yellow key must be referenced, followed by orange. Since the final array is an indexed array, the string cat is the second value and, therefore, has an index key of 1. Therefore, the correct answer is E.
What will the $array array contain at the end of the execution of the following script? <?php $array = array ('1', '1'); foreach ($array as $k => $v) { $v = 2; } ?> A. array ('2', '2') B. array ('1', '1') C. array (2, 2) D. array (Null, Null) E. array (1, 1)
Answer B is correct. The foreach construct operates on a copy of $array and, therefore, no changes are made to its original values.
Assume you would like to sort an array in ascending order by value while preserving key associations. Which of the following PHP sorting functions would you use? A. ksort() B. asort() C. krsort() D. sort() E. usort()
Only the asort function sorts an array by value without destroying index associations. Therefore, Answer B is correct.
What is the name of a function used to convert an array into a string? Your Answer: _____________________
The serialize function takes a complex data structure and returns a string that can later be used by the unserialize function to reconstruct the original data structure. A valid answer to this question could also be the implode function, which concatenates each element of an array with a “glue” string.
In what order will the following script output the contents of the $array array? <?php $array = array ('a1', 'a3', 'a5', 'a10', 'a20'); natsort ($array); var_dump ($array); ?> A. a1, a3, a5, a10, a20 B. a1, a20, a3, a5, a10 C. a10, a1, a20, a3, a5 D. a1, a10, a5, a20, a3 E. a1, a10, a20, a3, a5
The natsort() function uses a “natural ordering” algorithm to sort the contents of an array, rather than a simple binary comparison between the contents of each element. In fact, in this example the array is not even touched, since its elements are already in what could be considered a “natural” order. Therefore, Answer A is correct.
Which function would you use to rearrange the contents of the following array so that they are reversed (i.e.: array ('d', 'c', 'b', 'a') as the final result)? (Choose 2) <?php $array = array ('a', 'b', 'c', 'd'); ?> A. array_flip() B. array_reverse() C. sort() D. rsort() E. None of the above
Despite its name, array_flip() only swaps each element of an array with its key. Both rsort() and array_reverse() would have the effect of reordering the array so that it contents would read ('d', 'c', 'b', 'a'). Therefore, the correct answers are B and D.
What will the following script output? <?php $array = array ('3' => 'a', '1b' => 'b', 'c', 'd'); echo ($array[1]); ?> A. 1 B. b C. c D. A warning. E. a
PHP starts assigning numeric keys to elements without a hard-coded key from the lowest numeric key available (even if that key is a numeric string). If you never specify a numeric key to start with, it starts from zero. In our script, however, we assigned the key '3' to the very first element, thus causing the interpreter to assign the key 4 to the third element and 5 to the last element. Note that the key '1b' is not considered numeric, because it doesn’t evaluate to an integer number. Therefore, element 1 doesn’t exist, and Answer D is correct.
What is the simplest method of computing the sum of all the elements of an array? A. By traversing the array with a for loop B. By traversing the array with a foreach loop C. By using the array_intersect function D. By using the array_sum function E. By using array_count_values()
The array_sum function calculates the sum of all the elements of an array. Therefore, Answer D is correct.
What will the following script output? <?php $array = array (0.1 => 'a', 0.2 => 'b'); echo count ($array); ?> A. 1 B. 2 C. 0 D. Nothing E. 0.3
The script will output 1 (Answer A). This is because only integer numbers and strings can be used as keys of an array—floating-point numbers are converted to integers. In this case, both 0.1 and 0.2 are converted to the integer number 0, and $array will only contain the element 0 => 'b'.
What elements will the following script output? <?php $array = array (true => 'a', 1 => 'b'); var_dump ($aray); ?> A. 1 => 'b' B. True => 'a', 1 => 'b' C. 0 => 'a', 1 => 'b' D. None E. It will output NULL
This question tries to attract your attention to a problem that doesn’t bear on its answer. The $array array will contain only one element, since true evaluates to the integer 1. However, there is a typo in the var_dump() statement—$array is misspelled as $aray, using only one ‘r’. Therefore, the var_dump() statement will output NULL (and, possibly, a notice, depending on your error settings). Answer E is correct.
Absent any actual need for choosing one method over the other, does passing arrays by value to a read-only function reduce performance compared to passing them by reference? A. Yes, because the interpreter must always create a copy of the array before passing it to the function. B. Yes, but only if the function modifies the contents of the array. C. Yes, but only if the array is large. D. Yes, because PHP must monitor the execution of the function to determine if changes are made to the array. E. No.
This question is a bit convoluted, so it’s easy to get lost in it. For starters, notice that it specifies two important assumptions: first, that you do not have any compelling reason for passing the array either way. If you needed a function to modify the array’s contents, you’d have no choice but to pass it by reference—but that’s not the case here. Second, the question specifies that we’re passing the array to a read-only function; if this were not the case, Answer B would be true, since a change of the array would cause an actual copy of the array to be created. As a general rule, however, passing an array by reference to a function that does not modify its contents is actually slower than passing it by value, since PHP must create a set of structures that it uses to maintain the reference. Because PHP uses a lazy-copy mechanism (also called copy-on-write) that does not actually create a copy of a variable until it is modified, passing an array by value is a very fast and safe method of sharing an array with a function and, therefore answer E is correct.
What will the following script output? <?php function sort_my_array ($array) { return sort ($array); } $a1 = array (3, 2, 1); var_dump (sort_my_array (&$a1)); ?> A. NULL B. 0 => 1, 1 => 2, 2 => 3 C. An invalid reference error D. 2 => 1, 1 => 2, 0 => 3 E. bool(true)
The correct answer is E. The sort function works directly on the array passed (by reference) to it, without creating a copy and returning it. Instead, it returns the Boolean value True to indicate a successful sorting operation (or False to indicate an error). Note that this example passes the $a1 array to sort_my_array() by reference; this technique is deprecated and the function should be re-declared as accepting values by reference instead.
What will be the output of the following script? <?php $result = ''; function glue ($val) { global $result; $result .= $val; } $array = array ('a', 'b', 'c', 'd'); array_walk ($array, 'glue'); echo $result; ?> Your Answer: ____________________________
The array_walk function executes a given callback function for every element of an array. Therefore, this script will cause the glue function to concatenate all the elements of the array and output abcd.
What will the following script output? <?php $array = array (1, 2, 3, 5, 8, 13, 21, 34, 55); $sum = 0; for ($i = 0; $i < 5; $i++) { $sum += $array[$array[$i]]; } echo $sum; ?> A. 78 B. 19 C. NULL D. 5 E. 0
This question is designed to test your ability to analyze a complex script more than your understanding of arrays. You may think it too convoluted—but we’ve all been faced with the not-so-pleasant task of debugging someone else’s code, and compared to some of the scripts we’ve seen, this is actually quite simple. The script simply cycles through the for loop five times, each time adding to $sum the value of the element of $array whose key is equal to the value of the element of $array whose key is equal to $i. It might sound a bit like a high-tech variation of “how much wood would a wood chuck chuck,” but if you step through the code manually, you’ll find that, when $i is zero, then $array[$array[$i]] becomes $array[$array[0]], or $array[1], that is, 2. Applied to all the iterations of the for loop, the resulting total is 78.