0

Why do PHP variables need to be pre-defined before a loop in order to use it inside of (and subsequently outside of) the loop?

foreach( $formats as $format => $src ){
    if ( !empty( $src ) ) {
        $source .= '<source type="' . $format . '" src="' . $src . '">';
    }
}
echo $source;

Shows "undefined variable" $source

foreach( $formats as $format => $src ){
    $source2 = '';
    if ( !empty( $src ) ) {
        $source2 .= '<source type="' . $format . '" src="' . $src . '">';
    }
}
echo $source2;

Returns only the last item in the variable but there is no undefined variable

Seems weird to me that it almost acts like a variable scope issue.

3
  • 6
    Not a scope issue; you just can’t append anything to something that doesn’t exist. And in your second example, you are setting the variable to an empty string in every loop iteration – you have to do it once, before. Commented Nov 12, 2015 at 21:00
  • well in php you can, it will complain, but do it anyway. good-old-php Commented Nov 12, 2015 at 21:05
  • Made a big change on the examples because I wasn't sure if the examples i used actually demonstrated what I was trying to express. Commented Nov 12, 2015 at 21:49

1 Answer 1

5

Because you are trying to concatenate a string to something that's not a string (or at least not yet) by doing:

$source .= '<source type="' . $format . '" src="' . $src . '">';
      //^ this dot means concat.

And in your second example, you are resetting your variable to an empty string in each iteration, the declaration should be outside, before the loop instead:

$source2 = '';
foreach( $formats as $format => $src ){   
    if ( !empty( $src ) ) {
        $source2 .= '<source type="' . $format . '" src="' . $src . '">';
    }
}
echo $source2;

As @drew010 stated in his comment, the variable will be actually created by php but you will get the notice displayed (if you have your php settings so that they will be shown).

Sign up to request clarification or add additional context in comments.

4 Comments

And to elaborate on the OP, technically it doesn't have to be declared before the loop. Undefined variable is just a notice. The end result is that the variable gets created and appended to with a side effect of a PHP notice being generated. Doing this is bad practice so you should declare source as an empty string before going into the loop.
Thanks! I've added an explanation to my answer.
Also, 3v4l.org/cZL7O shows no error for the array append from over 150 different versions of php 4.3-7.0
Made a big change on the examples because I wasn't sure if the examples i used actually demonstrated what I was trying to express.

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.