Thompson
Thompson

Reputation: 2000

Checking value in an multi-dim array?

My array is like:

Array
(
    [0] => Array
        (
            [id] => 6
            [name] => Name1
        )
    [1] => Array
        (
            [id] => 7
            [name] => Name2
        )
)            

How can I check any perticular value of name exists in this multi-dimentional array?

Upvotes: 0

Views: 79

Answers (5)

This function will help you,

<?php

    function multi_dim_array_search($array,$col,$val)
    {
        foreach($array as $elem)
            if($elem[$col] == $val)
                return true;

            return false;
    }


    $array = array(
        array('id' => 1,'name' => 'Name1'),
        array('id' => 2,'name' => 'Name2')
    );

    //usage
    var_dump(multi_dim_array_search($array,'name','Name1')); //true
    var_dump(multi_dim_array_search($array,'name','Name2')); //true
    var_dump(multi_dim_array_search($array,'name','Name3')); //false


?>

Upvotes: 0

Corbin
Corbin

Reputation: 33437

With that structure, your only option is essentially a linear search:

$found = null;
foreach ($arr as $idx => $elem) {
    if ($elem['name'] == $searchName) {
        $found = $idx;
    }
}
if ($found !== null) {
    echo "Found $searchName at $idx.";
}

Upvotes: 0

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

Iterate.

function multi_in_array($name, $array) {
    foreach ($array as $sub_array) {
        if (in_array($name, $array)) {
            return true;
        }
    }
    return false;
}

Upvotes: 1

Andreas Wong
Andreas Wong

Reputation: 60516

function checkName($haystack, $needle) {
   foreach($haystack as $hay) {
      if($hay['name'] == $needle) {
         return true;
      }
   }
   return false;
}

Upvotes: 1

Darvex
Darvex

Reputation: 3644

perhaps you're looking for in_array function?

Upvotes: 0

Related Questions