PHP Array Iteration

An EasierWay to Iterate
As you can see, using this set of functions requires quite a bit of work; to be fair, there are some situations where they offer the only reasonable way of iterating through an array, particularly if you need to skip back-and-forth between its elements.
If, however, all you need to do is iterate through the entire array fromstart to finish, PHP provides a handy shortcut in the formof the foreach() construct:

<?php
$array = array('foo', 'bar', 'baz');
foreach($array as $key => $value) {
echo "$key: $value";
}
?>
The process that takes place here is rather simple, but has a few important gotchas. First of all, foreach operates on a copy of the array itself; this means that changes made to the array inside the loop are not reflected in the iteration—for example, removing an item from the array after the loop has begun will not cause foreach to skip over that element. The array pointer is also always reset to the beginning of the array prior to the beginning to the loop, so that you cannot manipulate it in such a way to cause foreach to start from a position other than the first element of the array.
PHP 5 also introduces the possibility of modifying the contents of the array directly by assigning the value of each element to the iterated variable by reference rather than by value:
<?php
$a = array(1, 2, 3);
foreach($a as $k => &$v){
$v += 1;
}
var_dump($a); // $a will contain (2, 3, 4)
?>
While this technique can be useful, it is so fraught with peril as to be something best left alone.
Consider this code, for example:
<?php
$a = array ('zero','one','two');
foreach($a as &$v) {}
foreach($a as $v) {}
print_r($a);
?>
It would be natural to think that, since this little script does nothing to the array, it will not affect its contents… but that’s not the case! In fact, the script provides the following output:
Array(
[0] => zero
[1] => one
[2] => one
)
As you can see, the array has been changed, and the last key now contains the value ’one’. How is that possible? Unfortunately, there is a perfectly logical explanation— and this is not a bug. Here’s what going on. The first foreach loop does not make any change to the array, just as we would expect. However, it does cause $v to be assigned a reference to each of $a’s elements, so that, by the time the loop is over,$v is, in fact, a reference to $a[2].
As soon as the second loop starts, $v is now assigned the value of each element. However, $v is already a reference to $a[2]; therefore, any value assigned to it will be copied automatically into the last element of the arrays! Thus, during the first iteration, $a[2] will become zero, then one, and then one again, being effectively copied on to itself. To solve this problem, you should always unset the variables you use in your by-reference foreach loops—or, better yet, avoid using the  former altogether.
Passive Iteration
The array_walk() function and its recursive cousin array_walk_recursive() can be used to perform an iteration of an array in which a user-defined function is called. Here’s an example:
<?php
function setCase(&$value, &$key){
$value = strtoupper($value);
}

$type = array('internal', 'custom');
$output_formats[] = array('rss', 'html', 'xml');
$output_formats[] = array('csv', 'json');
$map = array_combine($type, $output_formats);
array_walk_recursive($map, 'setCase');
var_dump($map);
?>
Using the custom setCase() function, a simplewrapper for strtoupper(), we are able to convert each each of the array’s values to uppercase. One thing to note about array_walk_recursive() is that it will not call the user-defined function on anything but scalar values; because of this, the first set of keys, internal and custom, are never passed in.
The resulting array looks like this:
array(2) {
["internal"]=>
&array(3) {
[0]=>
string(3) "RSS"
[1]=>
string(4) "HTML"
[2]=>
string(3) "XML"
}
["custom"]=>
&array(2) {
[0]=>
string(3) "CSV"
[1]=>
string(4) "JSON"
}
}

23 comments:

  1. I have seen that all will say the same thing repeatedly. But in your blog, I had a chance to get some useful and unique information. I would like to suggest your blog in my dude circle. please keep on updates. hope it might be much useful for us. keep on updating.
    PHP Training in Chennai

    ReplyDelete
  2. • Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing your valuable information and time. Please keep updatingAzure Online course Bangalore

    ReplyDelete
  3. I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.
    Best Devops Training in pune
    Devops interview questions and answers

    ReplyDelete
  4. Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
    python course in pune
    python course in chennai
    python Training in Bangalore

    ReplyDelete
  5. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject

    rpa training in chennai |best rpa training in chennai|
    rpa training in bangalore | best rpa training in bangalore

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. such a wonderful blog to know more new things

    BEST ANGULAR JS TRAINING IN CHENNAI WITH PLACEMENT

    https://www.acte.in/angular-js-training-in-chennai
    https://www.acte.in/angular-js-training-in-annanagar
    https://www.acte.in/angular-js-training-in-omr
    https://www.acte.in/angular-js-training-in-porur
    https://www.acte.in/angular-js-training-in-tambaram
    https://www.acte.in/angular-js-training-in-velachery

    ReplyDelete
  8. Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
    oracle training in chennai

    oracle training in omr

    oracle dba training in chennai

    oracle dba training in omr

    ccna training in chennai

    ccna training in omr

    seo training in chennai

    seo training in omr




    ReplyDelete
  9. I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favourites blog site list and will be checking back soon.
    Angular js Training in Chennai

    Angular js Training in Velachery

    Angular js Training in Tambaram

    Angular js Training in Porur

    Angular js Training in Omr

    Angular js Training in Annanagar

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...