Maybe the serial articles should be called "two questions every two days"
--by author
11. Consider the following segment of code:
<?php
define("STOP_AT", 1024);
$result = array();
/* Missing code */
{
$result[] = $idx;
}
print_r($result);
?>
What should go in the marked segment to produce the following array output?
Array
{
[0] => 1
[1] => 2
[2] => 4
[3] => 8
[4] => 16
[5] => 32
[6] => 64
[7] => 128
[8] => 256
[9] => 512
}
A. foreach($result as $key => $val)
B. while($idx *= 2)
C. for($idx = 1; $idx < STOP_AT; $idx *= 2)
D. for($idx *= 2; STOP_AT >= $idx; $idx = 0)
E. while($idx < STOP_AT) do $idx *= 2
Answer:
As it is only possible to add a single line of code to the segment provided, the only statement that makes sense is a for loop, making the choice either C or D. In order to select the for loop that actually produces the correct result, we must first of all revisit its structural elements. In PHP, for loops are declared as follows:
for (<init statement>; <continue until statement>; <iteration statement>)
where the <init statement> is executed prior to entering the loop. The for loop then begins executing the code within its code block until the <continue until> statement evaluates to False. Every time an iteration of the loop is completed, the <iteration statement> is executed.
Applying this to our code segment, the correct for statement is:
for ($idx = 1; $idx < STOP_AT; $idx *= 2) or answer C.
12. Choose the appropriate function declaration for the user-defined function is_leap(). Assume that, if not otherwise defined, the is_leap function uses the year 2000 as a default value:
<?php
/* Function declaration here */
{
$is_leap = (!($year %4) && (($year % 100) || !($year % 400)));
return $is_leap;
}
var_dump(is_leap(1987)); /* Displays false */
var_dump(is_leap()); /* Displays true */
?>
A. function is_leap($year = 2000)
B. is_leap($year default 2000)
C. function is_leap($year default 2000)
D. function is_leap($year)
E. function is_leap(2000 = $year)
Answer:
12. Of the five options, only two are valid PHP function declarations (A and D). Of these two declarations, only one will provide a default parameter if none is passed—Answer A.