Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP's For-each / for behaviour – Value remains accesible after Foreach ends

I have this piece of code:

$exists = false;
foreach ($outsiderTests as $key => $outsiderTest) {
   $textExists = null;
   foreach ($tests as $test) {
       if ($outsiderTest->getName() == $test->getName()) {
           $exists = true;
           $existingTest = $test;
           break;
       } else
           $exists = false;
   }

   var_dump($existingTest, $test);
}

As you can see, I want to see if there is an equivalent to an outsiderTest in $tests array. I thought I would have to save the existing equivalent $test on another variable as it would be gone after the foreach ends, but it does not.

The value of $existingTest and $test is the same when I dump them. This is cool, and makes me able to get rid of the mentioned $existingTest variable, but makes me wonder if I am understanding PHP’s loop functionality.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Doesn’t the $test variable only exist inside the foreach scope? Does PHP temporarily save the value of the last index the execution has run through?

>Solution :

PHP’s variable scope is explained here: https://www.php.net/manual/en/language.variables.scope.php

Effectively you have 2 scopes:

  • The global scope
  • The local function scope

So a loop variable will be accessible out of it’s scope and will contain the last value it had. This is why you got this behaviour.

If you have a loop calling a function then you have multiple options:

  • Declare the external variable with the global keyword inside the function.
  • Access globals with the $GLOBALS variable.
  • Pass the globals you need to your anonymous function with the use () syntax.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading