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
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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.