Jump to content

strange foreach loop output


steadythecourse

Recommended Posts

Hi!

This bit of code does exactly what I want it to just not sure why.

 

The way I would (***_u_me) this code to be written would be to replace the

echo ($array_2[$index]); with echo ($array_2[$value]); to get the output I'm

getting. Basically the foreach loop loops through $array_1 when it finds a key with a null value it outputs the $value or the $index which ever I decide to output of $array_2 which corresponds to that value. when I echo ($array_2[$value]) I get no output and when I echo ($array_2[$index]) I get the wanted output below. It doesn't seem right

 

 


<?php

function test() {
  $array_1 = array("Matt" => NULL, "Kim" => 1, "Jessica" => NULL, "Keri" => 1);
  $array_2 = array("Matt","Kim","Jessica","Keri");
  foreach ($array_2 as $index => $value) {
    if (!isset($array_1[$value])) {
      echo ($array_2[$index]);
      echo "<br />";
    }
  }
}

test();

?>

 

output

 

Matt

Jessica

 

Thanks,

steadythecourse

 

Link to comment
https://forums.phpfreaks.com/topic/215706-strange-foreach-loop-output/
Share on other sites

makes sense to me...

 

<?php

function test() {
  $array_1 = array("Matt" => NULL, "Kim" => 1, "Jessica" => NULL, "Keri" => 1);
  $array_2 = array("Matt","Kim","Jessica","Keri");
  foreach ($array_2 as $index => $value) {
  	echo "index: $index - value: $value <br />";
  
    if (!isset($array_1[$value])) {
    	echo "array_1[$value] is NOT set <br />";
      echo ($array_2[$index]);
      echo "<br />";
    } else {
        	echo "array_1[$value] is set and is " . $array_1[$value] . "<br />";
    }
  }
}

test();

?>

 

 

output:

 

index: 0 - value: Matt

array_1[Matt] is NOT set

Matt

index: 1 - value: Kim

array_1[Kim] is set and is 1

index: 2 - value: Jessica

array_1[Jessica] is NOT set

Jessica

index: 3 - value: Keri

array_1[Keri] is set and is 1

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.