Skip to main content

How is an array in a PHP foreach loop read?


We have all heard of how in a for loop, we should do this:




for ($i = 0, $count = count($array); $i < $c; ++$i)
{
// Do stuff while traversing array
}



instead of this:




for ($i = 0; $i < count($array); ++$i)
{
// Do stuff while traversing array
}



for performance reasons (i.e. initializing $count would've called count() only once, instead of calling count() with every conditional check).



Does it then also make a difference if, in a foreach loop, I do this:




$array = do_something_that_returns_an_array();

foreach ($array as $key => $val)
{
// Do stuff while traversing array
}



instead of this:




foreach (do_something_that_returns_an_array() as $key => $val)
{
// Do stuff while traversing array
}



assuming circumstances allow me to use either? That is, does PHP call the function only once in both cases, or is it like for where the second case would call the function again and again?


Source: Tips4allCCNA FINAL EXAM

Comments

  1. foreach() is implemented using iterators - thus it only calls the function that returns an array once, and then uses the iterator which points to the existing result set to continue with each item.

    ReplyDelete
  2. foreach makes a copy of the input array and works on that in each iteration. So you can use foreach (do_something_that_returns_an_array() as $key => $val) and it'll call do_something_that_returns_an_array() only once.

    ReplyDelete
  3. I think testing it will surely answer that.

    Here is my code:

    <?php

    function GetArray() {
    echo "I am called.\n";
    return array("One"=>1, "Two"=>2, "Three"=>3, "Four"=>4, "Five"=>5);
    }

    echo "Case #1\n";
    $array = GetArray();
    foreach ($array as $key => $val){
    // Do stuff while traversing array
    echo " Inside the loop: $key => $val\n";
    }
    echo "\n";

    echo "Case #2\n";
    foreach (GetArray() as $key => $val) {
    // Do stuff while traversing array
    echo " Inside the loop: $key => $val\n";
    }
    echo "\n";


    and here is the result:


    Case #1
    I am called.
    Inside the loop: One => 1
    Inside the loop: Two => 2
    Inside the loop: Three => 3
    Inside the loop: Four => 4
    Inside the loop: Five => 5

    Case #2
    I am called.
    Inside the loop: One => 1
    Inside the loop: Two => 2
    Inside the loop: Three => 3
    Inside the loop: Four => 4
    Inside the loop: Five => 5


    They both read call function once. So no different.

    ReplyDelete
  4. I would set up an example to see what happens. Something like...

    function do_something_that_returns_an_array() {
    echo 'I have been called!';
    return array('i am an', 'array');
    }


    As you can see on CodePad, it is only being called once.

    ReplyDelete
  5. I've always assumed that do_something_that_returns_an_array() only runs once because, unlike in the for loop, there's no reason for it to run multiple times. The reason the for loop truth checker runs at the end of every iteration is to allow for very complicated checkers.

    As a test, I did the following:

    function get_array() {echo 5; return array(1,2,3,4,5);}
    foreach(get_array() as $key => $value) {}


    The script printed 5 once. Therefore, the function get_array() only evaluates once.

    ReplyDelete
  6. foreach() works with Iterator or IteratorAggregate objects (e.g., arrays and objects implementing the interface). It can't work with immutable objects. Functions return immutable objects, so the returning array have to be copied into Iterator object before foreaching (it's made by php itself)

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.