strange foreach loop output

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
steadythecourse
Forum Newbie
Posts: 5
Joined: Tue Oct 05, 2010 11:46 am

strange foreach loop output

Post by steadythecourse »

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

Code: Select all


<?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
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: strange foreach loop output

Post by Jonah Bron »

It sounds like this is what you want?

Code: Select all

$array_1 = array("Matt" => NULL, "Kim" => 1, "Jessica" => NULL, "Keri" => 1);
foreach ($array_1 as $index => $value) {
  if ($value == null) {
    echo $index . '<br />';
  }
}
Post Reply