1

I was wondering if using

foreach(get_some_array() as $boo) do_something...

is slower than

$arr = get_some_array();
foreach($arr as $boo) do_something...

I mean would get_some_array() be called like 10000000 times if the array would have so many elements (in the 1st example) ?

1

2 Answers 2

6

No, that function will be called just 1 time. You can verify this by doing:

<?php
function get()
{
    echo "getting\n";

    return array('a', 'b', 'c', 'd');
}

foreach (get() as $v) {
    echo $v . "\n";
}
?>

Here it outputs:

murilo@mac:regionais$ php -f teste.php 
getting
a
b
c
d
Sign up to request clarification or add additional context in comments.

Comments

1

$arr = get_some_array(); theoretically adds zero time to this equation, so it really wont make a difference what you use here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.