Home > PHP > Finding Element in an Array of Arrays

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:

$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
    )
);

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:

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

Here is how we use the function for example:

echo in_array_of_arrays("ujang", $data);

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

?>

 

Technorati Tags: ,

Akhmad Daniel Sembiring

vITraining.com – Qualified IT Products, Outsourcing, and Services

Ligarwangi.com – Linux, E-book, Coffee, Gift, etc

  • Share/Bookmark
Categories: PHP Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Ikutilah Seminar GPS! "MEMBONGKAR RAHASIA BISNIS GPS TRACKING" - Pembicara : Ir. Akhmad Daniel Sembiring (CEO Vitraining.com & GpsTrackingIndonesia.com) - Bandung, Sabtu 25 September 2010 - Hotel Arion Swiss - Belhotel, Jl. Otto Iskandardinata No. 16 Bandung - Biaya Pendaftaran : 2 Jt (sebelum 18 September 2010 HANYA 1 Jt) - Register ONLINE : seminar-gps.vitraining.com - More Info e-mail to : info@gpstrackingindonesia.com

This site uses a Hackadelic PlugIn, Hackadelic SEO Table Of Contents 1.6.0.