日历

« 2008-08-30  
     12
3456789
10111213141516
17181920212223
24252627282930
31      

RSS订阅

  • 每日一题(19)

    2007-10-30 15:15:49

    (For I am going to travel on business next week, I have to add more questions in everyday's blog, maybe will absent for over a month and you should digest more before I am away!)


    Working with Arrays

    Questions

    1. 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

    Answer

    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.

     

    2. 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]

    Answer:

    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.

     

    3. What will the $array array contain at the end of the execution of the following scrīpt?

    <?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:

    Answer B is correct. The foreach construct operates on a copy of $array and, therefore, no changes are made to its original values.

     

    4. 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()

    Answer:

    Only the asort function sorts an array by value without destroying index associations. Therefore, Answer B is correct.

     

    5. What is the name of a function used to convert an array into a string?

    Your Answer: ____________________________

    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.

     

    6. In what order will the following scrīpt 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

    Answer:

    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.

     

    7. 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

    Answer:

    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.

     

    8. What will the following scrīpt output?

    <?php

    $array = array ('3' => 'a', '1b' => 'b', 'c', 'd');

    echo ($array[1]);

    ?>

    A. 1

    B. b

    C. c

    D. A warning.

    E. a

    Answer:

     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 scrīpt, 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 doesnt evaluate to an integer number. Therefore, element 1 doesnt exist, and Answer D is correct.

     

    9. 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()

    Answer:

    The array_sum function calculates the sum of all the elements of an array. Therefore, Answer D is correct.

     

    10. What will the following scrīpt output?

    <?php

    $array = array (0.1 => 'a', 0.2 => 'b');

    echo count ($array);

    ?>

    A. 1

    B. 2

    C. 0

    D. Nothing

    E. 0.3

    Answer:

    The scrīpt will output 1 (Answer A). This is because only integer numbers and strings can be used as keys of an arrayfloating-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'.

     

    11. What elements will the following scrīpt 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

    Answer:

    This question tries to attract your attention to a problem that doesnt 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.

     

    12. 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.

    Answer:

    This question is a bit convoluted, so its 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 arrays contents, youd have no choice but to pass it by referencebut thats not the case here. Second, the question specifies that were 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.

     

    13. What will the following scrīpt 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)

    Answer:

    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.

     

    14. What will be the output of the following scrīpt?

    <?php

    $result = '';

    function glue ($val) {

    global $result;

    $result .= $val;

    }

    $array = array ('a', 'b', 'c', 'd');

    array_walk ($array, 'glue');

    echo $result;

    ?>

    Your Answer: ____________________________

    Answer:

    The array_walk function executes a given callback function for every element of an array. Therefore, this scrīpt will cause the glue function to concatenate all the elements of the array and output abcd.

     

    15. What will the following scrīpt 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

    Answer:

    This question is designed to test your ability to analyze a complex scrīpt more than your understanding of arrays. You may think it too convolutedbut weve all been faced with the not-so-pleasant task of debugging someone elses code, and compared to some of the scrīpts weve seen, this is actually quite simple. The scrīpt 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, youll 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.

  • 每日一题(18)

    2007-10-29 22:50:03

    13. When you write a cookie with an expiration date in the future to a particular machine, the cookie never seem to be set. The technique usually works with other computers, and you have checked that the time on the machine corresponds to the time on the server within a reasonable margin by verifying the date reported by the operating system on the client computers desktop. The browser on the client machine seems to otherwise work fine on most other websites. What could be likely causes of this problem? (Choose 2)

    A. The browsers binaries are corrupt

    B. The client machines time zone is not set properly

    C. The user has a virus-scanning program that is blocking all secure cookies

    D. The browser is set to refuse all cookies

    E. The cookie uses characters that are discarded all data from your server

    Answer:

    Answers A and D both describe likely causes of this type of problem and warrant further investigation on your part. Since the browser seems to work fine, its unlikely that its binaries have suffered corruption such that only your site has stopped working, and virusscanning programs do not normally stop secure cookies selectively (although some block all cookies). On the other hand, the browser might have been explicitly set to refuse all cookies, which is probably the first source of trouble you should check for. By the same token, the computers time zone might have been set incorrectly and, since cookie expiration dates are coordinated through GMT, cause the cookie to expire as soon as it was set and never be returned to your scrīpts.

     

    14. Assuming that the client browser is never restarted, how long after the last access will a session expire and be subject to garbage collection?

    A. After exactly 1,440 seconds

    B. After the number of seconds specified in the session.gc_maxlifetime INI setting

    C. It will never expire unless it is manually deleted

    D. It will only expire when the browser is restarted

    E. None of the above

    Answer:

    The session.gc_maxlifetime INI setting regulates the amount of time since the last access after which the session handler considers a session data file garbage and marks it for deletion by the garbage handler. Once this has happened, any subsequent access to the session will be considered invalid, even if the data file still exists. Coincidentally, the session.gc_maxlifetime is set to 1,440 seconds, but you canturely on that number as it might have been changed without your knowledge by the system administrator. Answer B is, therefore, correct.

     

     

    15. The ___________ function automatically transforms newline characters into HTML <br /> tags

    Your Answer: ____________________________

    Answer:

    This identifies the nl2br function, which can be used precisely for this purpose.

    note:

    We have completed work on this section and will begin next section 'Working with Arrays' next time. Enjoy it! Enjoy PHP!
  • 每日一题(17)

    2007-10-28 21:40:45

    11. What will the following scrīpt output?

    <?php

    ob_start();

    for ($i = 0; $i < 10; $i++) {

    echo $i;

    }

    $output = ob_get_contents();

    ob_end_clean();

    echo $ouput;

    ?>

    A. 12345678910

    B. 1234567890

    C. 0123456789

    D. Nothing

    E. A notice

    Answer:

    Yet another question designed to see how well you recognize bugs in a scrīpt. Did you notice that, at the end of the scrīpt, the $output variables name is misspelled in the echo statement? The scrīpt will output a notice and, therefore, Answer E is correct.

    (Do you feel most funny? I think a great many guys will pick c (Including myself!), but the auther gave us a surprise! Without his explanation, you would think I lose a letter in word 'output') 


    12. By default, PHP stores session data in ________________.

    A. The filesystem

    B. A database

    C. Virtual memory

    D. Shared memory

    E. None of the above

    Answer:

    The filesystem (Answer A). By default, PHP stores all session information in the /tmp folder; users of operating systems where this folder doesnt exist (such as Windows) must change the default value of the session.save_path php.ini setting to a directory appropriate for their setup (e.g.: C:\Temp).

  • 每日一题(16)

    2007-10-27 03:19:01

    9. What happens when a form submitted to a PHP scrīpt contains two elements with the same name?

    A. They are combined in an array and stored in the appropriate superglobal array

    B. The value of the second element is added to the value of the first in the appropriate superglobal array

    C. The value of the second element overwrites the value of the first in the appropriate superglobal array

    D. The second element is automatically renamed

    E. PHP outputs a warning

     

    Answer:

    PHP simply adds elements to the appropriate superglobal array as they are retrieved from the query string or POST information. As a result, if two elements have the same name, the first one will just be overwritten by the second. Therefore, Answer C is correct.

     

    10. How would you store an array in a cookie?

    A. By adding two square brackets ([]) to the name of the cookie

    B. By using the implode function

    C. It is not possible to store an array in a cookie due to storage limitations

    D. By using the serialize function

    E. By adding the keyword ARRAY to the name of the cookie

     

    Answer:

    Only Answer B is always correct. While the implode function can be used to convert an array into a string in a prerequisite of being able to store it in a cookie. it cannot guarantee that you will be able to reconstruct the array at a later date the way serialize() can. Storing an array in a cookie may not be a good idea because browsers only allow a limited amount of storage space for each cookie, but that's not always the case--you should be able to store relatively small arrays without much in the way of problems.

     

  • 每日一题(15)

    2007-10-25 20:13:20

    7. Consider the following form and subsequent scrīpt. What will the scrīpt print out if the user types the word “php” and “great” in the two text boxes respectively?

    <form action="index.php" method="post">

    <input type="text" name="element[]">

    <input type="text" name="element[]">

    </form>

    <?php

    echo $_GET['element'];

    ?>

    A. Nothing

    B. Array

    C. A notice

    D. phpgreat

    E. greatphp

    Answer:

    Since the form is submitted using a POST HTML transaction, whatever values are typed in the text boxes are only going to be available in the $_POST superglobal array. Therefore, Answer C is correct, since the $_GET array won’t contain any values and PHP will issue a notice to this effect.

     

    8. In an HTTPS transaction, how are URLs and query strings passed from the browser to the web server?

    A. They are passed in clear text, and the subsequent transaction is encrypted

    B. They are encrypted

    C. The URL is left in clear text, while the query string is encrypted

    D. The URL is encrypted, while the query string is passed in clear text

    E. To ensure its encryption, the query string is converted into a header and passed along with the POST information

    Answer:

    When an HTTPS transaction takes place, the browser and the server immediately negotiate an encryption mechanism so that any subsequent data is not passed in clear text—including the URL and query string, which are otherwise passed the same way as with a traditional HTTP transaction. Answer B is, therefore, correct.

  • 每日一题(14)

    2007-10-24 21:03:15

    5. What will be the net effect of running the following scrīpt on the $s string? (Choose 2)

    <?php

    $s = '<p>Hello</p>';

    $ss = htmlentities ($s);

    echo $s;

    ?>

    A. The string will become longer because the angular brackets will be converted to their HTML meta character equivalents

    B. The string will remain unchanged

    C. If the string is printed to a browser, the angular brackets will be visible

    D. If the string is printed to a browser, the angular brackets will not be visible and it will be interpreted as HTML

    E. The string is destroyed by the call to htmlentities()

    Answer:

    This question tests nothing about your knowledge of HTML encoding—and everything about your ability to properly interpret code. The $s function is left unaltered by the call to htmlentities(), which returns the modified string so that it can be assigned to $ss. Therefore, Answers B and D are correct. If you’re wondering whether this is an unfair “trick” question, do keep in mind that, often, the ability to find and resolve bugs revolves around discovering little mistakes like this one.

     

    6. If no expiration time is explicitly set for a cookie, what happens to it?

    A. It expires right away

    B. It never expires

    C. It is not set

    D. It expires at the end of the user’s browser session

    E. It expires only if the scrīpt doesn’t create a server-side session

    Answer:

    Cookies automatically expire at the end of the user’s browser session if no explicit expiration time is set. Cookies are not necessary to maintain a server-side session, so answer D is correct.

     

  • 每日一题(13)

    2007-10-23 21:44:26

    3. Under normal circumstances—and ignoring any browser bugs—how can a cookie be accessed from a domain other than the one it was set for?

    A. By consulting the HTTP_REMOTE_COOKIE header

    B. It cannot be done

    C. By setting a different domain when calling setcookie()

    D. By sending an additional request to the browser

    E. By using Javascrīpt to send the cookie as part of the URL

    Answer:

    Answer B is correct. Browsers simply do not allow an HTTP transaction that takes place on one domain to set cookies for another domain. Doing otherwise would present clear security implications: for example, a malicious page on one domain could overwrite your session ID for another domain and force you to use another session to which a third party has access without your knowledge.

     

    4. How can the index.php scrīpt access the email form element of the following HTML form? (Choose 2)

    <form action="index.php" method="post">

    <input type="text" name="email"/> </form>

    A. $_GET['email']

    B. $_POST['email']

    C. $_SESSION['text’]

    D. $_REQUEST['email']

    E. $_POST['text']

    Answer:

    Since the form’s method is post, the scrīpt will only be able to read the value through the $_POST and $_REQUEST superglobal arrays. The element’s name (email) is used as the key for the value in the array and, therefore, Answers B and D are correct. Note that, although perfectly valid from a logical perspective, the use of $_REQUEST should be discouraged because of potential security implications.

  • 每日一题(12)

    2007-10-22 20:05:18

    1. How are session variables accessed?

    A. Through $_GET

    B. Through $_POST

    C. Through $_REQUEST

    D. Through global variables

    E. None of the above

     

    Answer:

        Although session data can be accessed using the global variables if the register_globals INI setting is turned on, the exam uses a version of PHP configured using the default php.ini file found in the official PHP distribution. In recent versions of PHP, the register_globals setting is turned off by default because of its serious security implications. As a result, Answer E is correct.

     

    2. What function causes the following header to be added to your server’s output?

    Set-Cookie: foo=bar;

    Your Answer: ____________________________

    Answer:

         Clearly, this question refers to the setcookie or setrawcookie functions, although the header function could be used as well.

  • 每日一题(11)

    2007-10-21 20:12:10

    (基础知识部分已完,下一次将开始新的章节:开发Web应用程序部分)

    19. Which of the following expressions multiply the value of the integer variable $a by 4?

    (Choose 2)

    A. $a *= pow (2, 2);

    B. $a >>= 2;

    C. $a <<= 2;

    D. $a += $a + $a;

    E. None of the above

    Answer:

    The correct answers are A and C. In Answer A, the pow function is used to calculate 2 2, which corresponds to 4. In Answer C, the left bitwise shift operator is used to shift the value of $a by two bits to the left, which corresponds to a multiplication by 4.

     

    20. How can a scrīpt come to a clean termination?

    A. When exit() is called

    B. When the execution reaches the end of the current file

    C. When PHP crashes

    D. When Apache terminates because of a system problem

    Answer:

    The only answer that really fits the bill is A. A scrīpt doesn’t necessarily terminate when it reaches the end of any file other than the main one—so the “current” file could be externally included and not cause the scrīpt to terminate at its end. As far as PHP and Apache crashes, they can hardly be considered “clean” ways to terminate a scrīpt.

  • 每日一题(10)

    2007-10-19 14:06:37

    17. The ____ operator returns True if either of its operands can be evaluated as True, but not both.

    Your Answer: ____________________________

    Answer:

     The right answer here is the exclusive-or (xor) operator.

     

    18. How does the identity ōperator === compare two values?

    A. It converts them to a common compatible data type and then compares the resulting values

    B. It returns True only if they are both of the same type and value If the two values are strings, it performs a lexical comparison

    C. It bases its comparison on the C strcmp function exclusively

    D. It converts both values to strings and compares them

    Answer:

    The identity operator works by first comparing the type of both its operands, and then their values. If either differ, it returns False—therefore, Answer B is correct.

  • 每日一题(9)

    2007-10-18 15:00:13

    15. Run-time inclusion of a PHP scrīpt is performed using the ________ construct, while compile-time inclusion of PHP scrīpts is performed using the _______ construct.

    A. include_once, include

    B. require, include

    C. require_once, include

    D. include, require

    E.All of the above are correct

    Answer:

    In recent versions of PHP, the only difference between require() (or require_once()) and include() (or include_once()) is in the fact that, while the former will only throw a warning and allow the scrīpt to continue its execution if the include file is not found, the latter will throw an error and halt the scrīpt. Therefore, Answer E is correct.

     

    16. Under what circumstance is it impossible to assign a default value to a parameter while declaring a function?

    A. When the parameter is Boolean

    B. When the function is being declared as a member of a class

    C. When the parameter is being declared as passed by reference

    D. When the function contains only one parameter

    E. Never

     

    Answer:

     

    When a parameter is declared as being passed by reference you cannot specify a default value for it, since the interpreter will expect a variable that can be modified from within the function itself. Therefore, Answer C is correct.

     

  • 每日一题(8)

    2007-10-17 22:21:12

    13. What is the value displayed when the following is executed? Assume that the code was executed using the following URL:

    testscrīpt.php?c=25

    <?php

    function process($c, $d = 25)

    {

    global $e;

    $retval = $c + $d - $_GET['c'] - $e;

    return $retval;

    }

    $e = 10;

    echo process(5);

    ?>

    A. 25

    B. -5

    C. 10

    D. 5

    E. 0

     

    Answer:

    This question is designed to test your knowledge of how PHP scopes variables when dealing with functions. Specifically, you must understand how the global statement works to bring global variables into the local scope, and the scope-less nature of superglobal arrays such as $_GET, $_POST, $_COOKIE, $_REQUEST and others. In this case, the math works out to 5 + 25 - 25 – 10, which is -5, or answer B.

     

    14. Consider the following scrīpt:

    <?php

    function myfunction($a, $b = true)

    {

    if($a && !$b) {

    echo "Hello, World!\n";

    }

    }

    $s = array(

    0 => "my",

    1 => "call",

    2 => '$function',

    3 => ' ',

    4 => "function",

    5 => '$a',

    6 => '$b',

    7 => 'a',

    8 => 'b',

    9 => '');

    $a = true;

    $b = false;

    /* Group A */

    $name = $s[?].$s[?].$s[?].$s[?].$s[?].$s[?];

    /* Group B */

    $name(${$s[?]}, ${$s[?]});

    ?>

     

    Each ? in the above scrīpt represents an integer index against the $s array. In order to display the Hello, World! string when executed, what must the missing integer indexes be?

    A. Group A: 4,3,0,4,9,9 Group B: 7,8

    B. Group A: 1,3,0,4,9,9 Group B: 7,6

    C. Group A: 1,3,2,3,0,4 Group B: 5,8

    D. Group A: 0,4,9,9,9,9 Group B: 7,8

    E. Group A: 4,3,0,4,9,9 Group B: 5,8

     

    Answer:

    Functions can be called dynamically by appending parentheses (as well as any parameter needed) to a variable containing the name of the function to call. Thus, for Group A the appropriate index combination is 0, 4, 9, 9, 9, 9, which evaluates to the string myfunction. The parameters, on the other hand, are evaluated as variables dynamically using the ${} construct. This means the appropriate indexes for group B are 7 and 8, which evaluate to ${'a'} and ${'b'}—meaning the variables $a and $b respectively. Therefore, the correct answer is D.

  • 每日一题(7)

    2007-10-16 12:34:57

    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.

  • 每日一题(6)

    2007-10-14 21:59:02

    9. Which language construct can best represent the following series of if conditionals?

    <?php

    if($a == 'a') {

    somefunction();

    } else if ($a == 'b') {

    anotherfunction();

    } else if ($a == 'c') {

    dosomething();

    } else {

    donothing();

    }

    ?>

     

    A. A switch statement without a default case

    B. A recursive function call

    C. A while statement

    D. It is the only representation of this logic

    E. A switch statement using a default case

     

    Answer:

    9. A series of if…else if code blocks checking for a single condition as above is a perfect place to use a switch statement:

    <?php

    switch($a) {

    case 'a':

    somefunction();

    break;

    case 'b':

    anotherfunction();

    break;

    case 'c':

    dosomething();

    break;

    default:

    donothing();

    }

    ?>

    Because there is a catch-all else condition, a default case must also be provided for that situation. Answer E is correct.

     

    10. What is the best way to iterate through the $myarray array, assuming you want to modify the value of each element as you do?

     

    <?php

    $myarray = array ("My String", "Another String", "Hi, Mom!");

    ?>

     

    A. Using a for loop

    B. Using a foreach loop

    C. Using a while loop

    D. Using a do…while loop

    E. There is no way to accomplish this goal

     

    Answer:

    Normally, the foreach statement is the most appropriate construct for iterating through an array. However, because we are being asked to modify each element in the array, this option is not available, since foreach works on a copy of the array and would therefore result in added overhead. Although a while loop or a do…while loop might work, because the array is sequentially indexed a for statement is best suited for the task, making Answer A correct:

    <?php

    $myarray = array ("My String", "Another String", "Hi, Mom!");

    for($i = 0; $i < count($myarray); $i++)

    {

    $myarray[$i] .= " ($i)";

    }

    ?>

     

  • 每日一题(5)

    2007-10-13 01:20:54

    7. Which values should be assigned to the variables $a, $b and $c in order for the following scrīpt to display the string Hello, World!?

    <?php

    $string = "Hello, World!";

    $a = ?;

    $b = ?;

    $c = ?;

    if($a) {

    if($b && !$c) {

    echo "Goodbye Cruel World!";

    } else if(!$b && !$c) {

    echo "Nothing here";

    }

    } else {

    if(!$b) {

    if(!$a && (!$b && $c)) {

    echo "Hello, World!";

    } else {

    echo "Goodbye World!";

    }

    } else {

    echo "Not quite.";

    }

    }

    ?>

    A. False, True, False

    B. True, True, False

    C. False, True, True

    D. False, False, True

    E. True, True, True

     

    Answer: Following the logic of the conditions, the only way to get to the Hello, World! string is in the else condition of the first if statement. Thus, $a must be False. Likewise, $b must be False. The final conditional relies on both previous conditions ($a and $b) being False, but insists that $c be True (Answer D).

     

    8. What will the following scrīpt output?

    <?php

    $array = '0123456789ABCDEFG';

    $s = '';

    for ($i = 1; $i < 50; $i++) {

    $s .= $array[rand(0,strlen ($array) - 1)];

    }

    echo $s;

    ?>

     


     

    A. A string of 50 random characters

    B. A string of 49 copies of the same character, because the random number generator has not been initialized

    C. A string of 49 random characters

    D. Nothing, because $array is not an array

    E. A string of 49 ‘G’ characters

     

    Answer: The correct answer is C. As of PHP 4.2.0, there is no need to initialize the random number generator using srand() unless a specific sequence of pseudorandom numbers is sought. Besides, even if the random number generator had not been seeded, the scrīpt would have still outputted 49 pseudo-random characters—the same ones every time. The $array variable,

    though a string, can be accessed as an array, in which case the individual characters corresponding to the numeric index used will be returned. Finally, the for loop starts from 1 and continues until $i is less than 50—for a total of 49 times.

  • 每日一题(4)

    2007-10-10 22:22:07

    5. What is the difference between print() and echo()?

    A. print() can be used as part of an expression, while echo() can’t

    B. echo() can be used as part of an expression, while print() can’t

    C. echo() can be used in the CLI version of PHP, while print() can’t

    D. print() can be used in the CLI version of PHP, while echo() can’t

    E. There’s no difference: both functions print out some text!

     

    Answer: A