Sajjad Khan
Sajjad Khan

Reputation: 345

Iterative multidimensional associative array using foreach loop in php

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.

Upvotes: 0

Views: 455

Answers (1)

bugwheels94
bugwheels94

Reputation: 31920

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;
}   
?>

Upvotes: 1

Related Questions