phparraysvariablesloopsforeach

Create joined string by looping through key value array


I am trying to use a variable in a foreach loop but I am getting strange results. The first foreach loop work fine but gives a notice of a undefined variable and in the second version there is no notice but it only returns the last item in the array.

$formats = array(
    'application/x-mpegurl' => 'hls',
    'video/webm'            => 'webm',
    'video/mp4'             => 'mp4',
    'video/ogg'             => 'ogg',
    'video/flash'           => 'flash',
);

// Works perfectly but there a undefined variable $source
foreach( $formats as $format => $src ){
    if ( !empty( $src ) ) {
        $source .= '<source type="' . $format . '" src="' . $src . '">';
    }
}
echo $source;

// Returns only the last item in the variable but there is no undefined variable
foreach( $formats as $format => $src ){
    $source2 = '';
    if ( !empty( $src ) ) {
        $source2 .= '<source type="' . $format . '" src="' . $src . '">';
    }
}
echo $source2;

I have googled for solutions have not found any.


Solution

  • Define $source an d $source1 before the loops start.

     $source = "";
     // loop starts here
    

    Complete code:

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