0

I want to search a particular record in a multidimensional associative array. It works fine when I search a record from the first array but it is not working properly when searching in the second array.

This is my code:

<?php
$year= array("January"=>array("Ben","Katty","Paul"),
"December"=>array("Ali","Adnan","Sajjad")
);
$match="Ali";
$notThere = True;

foreach ($year as $month => $person) {
    foreach ($person as $subjectName => $ID) {
        if($match==$ID){        
            echo "${ID}. borns on ${month}<br>";
            $notThere = false;
        }
    }
    if($notThere){
        echo "Not Found";
        $notThere=false;
    }   
}
?>

Not FoundAli. borns on December

Also, if you could explain how a nested foreach loop works.

5
  • What output are you expecting Commented Jun 28, 2015 at 20:44
  • not working show 0 born on january 0 born on December.. Commented Jun 28, 2015 at 20:44
  • i want is show not found or in case of true Ali born on January Commented Jun 28, 2015 at 20:45
  • but acc. to array Ali is born in Dec Commented Jun 28, 2015 at 20:46
  • first it output not found..then ali is born on December.. why it show not found first Commented Jun 28, 2015 at 20:51

1 Answer 1

1

You need to move your If statement out of loops

<?php
$year= array("January"=>array("Ben","Katty","Paul"),
"December"=>array("Ali","Adnan","Sajjad")
);
$match="Ali";
$notThere = True;

foreach ($year as $month => $person) {
    foreach ($person as $subjectName => $ID) {
        if($match==$ID){        
            echo "${ID}. borns on ${month}<br>";
            $notThere = false;
        }
    }
}
if($notThere){
    echo "Not Found";
    $notThere=false;
}   
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks now its work please explain how this nested loop work.. once i get key and value what need of another loop..
second loop iterate over the array( which contain names) of first loop

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.