Finding Element in an Array of Arrays
The listed PHP function can be used to find an element of an array that are a member of other array. For example we have a data structure like this:
Then we would like to find whether a user_id is found on inside the $data variable which is an array of arrays. To perform that operation we can use the following function:
{
foreach ($haystack as $id=>$a)
{
if(in_array($needle,$a))
{
return "$needle found in id $id";
}
}
return false;
}
Here is how we use the function for example:
And here is a complete source code for testing the function:
$data = array(
array(
"user_id" => "akhdaniel",
"group_id" => 1
),
array(
"user_id" => "amir",
"group_id" => 1
),
array(
"user_id" => "abyan",
"group_id" => 1
),
array(
"user_id" => "ujang",
"group_id" => 1
)
);
echo "<pre>";
echo in_array_of_arrays("ujang", $data);
function in_array_of_arrays($needle, $haystack)
{
foreach ($haystack as $id=>$a)
{
if(in_array($needle,$a))
{
return "$needle found in id $id";
}
}
return false;
}
?>
Akhmad Daniel Sembiring
vITraining.com – Qualified IT Products, Outsourcing, and Services
Ligarwangi.com – Linux, E-book, Coffee, Gift, etc




Recent Comments