每日一题(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)";

}

?>

 


相关阅读:

TAG: 每日一题

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

数据统计

  • 访问量: 17004
  • 日志数: 87
  • 建立时间: 2007-09-29
  • 更新时间: 2008-04-15

RSS订阅

Open Toolbar