$array='hello hello2';
foreach(explode(' ',$array) as $v)
echo $v;
How many times does explode get executed?
And is it better that to use another var like:
$exploded = explode(...);
foreach($exploded as $v)
...
?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It only gets executed once.
foreachwill operate on a copy of the return value ofexplode(array or false).foreachis a language construct which expects$array as $key => $value.$arraycan be any expression which evaluates to an array, andexplodeis such a function. The expression is evaluated only once, and then foreach operates on the result of the expression.This is different with a regular
forloop for instance. Aforloop takes three expressions. Both the second and third expression are evaluated for each iteration of the loop.So with a for loop there could be a difference (leaving optimization and the O(1)-performance of
countaside) between these two statements: