Question

The following is the best way to iterate through and modify array in PHP5.*+

(source: http://zend-php.appspot.com/questions_list -- question #3)

$array = array("one" => 1, "two" => 2, "three" => 3, "four" => 4, "five" => 5);
foreach($array as $key => &$val) {
   $val += 1;
}

What is it about this method of iterating and modifying that makes it better than others?

Can someone please explain how come this actually works?

This iterates just fine, why include as $key => &$val if we are not using the keys?, also why do we need to include the & in &$val:

foreach($array as $val){
   echo $val;
}

I appreciate the explanation, Thanks in advance!

Was it helpful?

Solution

Since they intend to modify the value, getting it as a reference is clever.

$array = array("one" => 1, "two" => 2, "three" => 3, "four" => 4, "five" => 5);
foreach($array as $key => &$val) {
   $val += 1;
}

Will add 1 to all values.

If you did:

foreach($array as $key => $val) {
   $val += 1;
}

Nothing would happen.

I strongly disagree that it is the best way though. I much prefer to see:

foreach($array as $key => $val) {
   $array[$key] += 1;
}

because it's much more straightforward. I'll gladly believe it doesn't perform as well, but I also don't care (unless there is a reason to start optimizing).

It's also worth mentioning that using references can lead to strange situations, such as: PHP reference causes data corruption

PS. I didn't downvote. I'm getting really annoyed by people downvoting and not leaving a comment.

OTHER TIPS

The question is as follows:

What is the best way to iterate and modify every element of an array using PHP 5?

These are the four choices listed in the link:

// method one
for($i = 0; $i < count($array); $i++) { 
    /* ... */ 
}

// method two
foreach($array as $key => &$val) { 
    /* ... */ 
}

// method three
foreach($array as $key => $val) { 
    /*... */ 
}

// method four
while(list($key, $val) = each($array)) { 
    /* ... */ 
}

The options 1, 3 and 4 are okay and they will work for iterating through the array. However, to modify the original array, you'll need to pass the $val by reference, which is what the second option does. That's why it's the preferred solution, in this case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top