25

Is there any php function such as in_array for associative arrays you get by the mysql function "mysql_fetch assoc" ?

For example, if I have an $array that looks like this:

array(0=>(array(ID=>1, name=>"Smith"), 1=>(array(ID=>2, name=>"John"))

Can I do something like in_array(key,value,array)?

Or in my case, if I am looking for the ID value of "1", in_array("ID",1,$array).

This is my solution, comment on it if you think it's the right way:

function in_assoc_array($key,$value,$array)
{
    if (empty($array))
        return false;
    else
    {
        foreach($array as $a)
        {
            if ($a[$key] == $value)
                return true;
        }
        return false;
    }
}
1
  • 1
    I think you want to compare the key/value pair with your given value. right? Commented Feb 16, 2014 at 8:53

7 Answers 7

50

In your case, I wonder if simply using isset() makes more sense, i.e.

isset($a[$key])
Sign up to request clarification or add additional context in comments.

2 Comments

isset we use when we know the key and array is designed in that way. sometimes we have to in_array for searching
Your light, simple and elegant solution works and that is how it should be. Thank You @Phil LaNAsa
22

Here is a one liner you can use.

$isInArray = in_array(1, array_column($names, 'ID'));

$isInArray = a Boolean (true or false) defining whether the value given was found within the column requested of the array in question.

1 = The value that is being searched for within the array.

$names = The array in question.

'ID' = The column within the array where we are searching for the value of 1.

1 Comment

that's perfectly works, saved my day, this is also perfect for 2 foreach loops and checkboxes populated using laravel projects
17

Try this..... You can use this function for any depth of the associated array. Just contraint to this function is that the key value would not be repeat any where in array.

<?php 
function is_in_array($array, $key, $key_value){
      $within_array = 'no';
      foreach( $array as $k=>$v ){
        if( is_array($v) ){
            $within_array = is_in_array($v, $key, $key_value);
            if( $within_array == 'yes' ){
                break;
            }
        } else {
                if( $v == $key_value && $k == $key ){
                        $within_array = 'yes';
                        break;
                }
        }
      }
      return $within_array;
}
$test = array(
                0=> array('ID'=>1, 'name'=>"Smith"), 
                1=> array('ID'=>2, 'name'=>"John")
        );
print_r(is_in_array($test, 'name', 'Smith'));
?>

4 Comments

I don't udnerstand why you wrote a new code, when there is a built-in function for that. You can see it below. On an other point the $k variable is waste of memory space, because it should check the value only.
@AndrewJarvis although it has been a while, why do you say that?
@JacobCohen A foreach loop on the top-level array and a simple if (isset($array["ID"]) && $array["ID"] === 1) {} will do the trick with much less code.
Nice answer ... works for me
10

You can't do it directly on nested arrays.. You need to nest it down a bit and then do it.

<?php
$arr=array(0=>array('ID'=>1, 'name'=>"Smith"), 1=>array('ID'=>2, 'name'=>"John"));

foreach($arr as $arr1)
{
    if(in_array(1,$arr1))
    {
       echo "Yes found.. and the correspoding key is ".key($arr1)." and the employee is ".$arr1['name'];
    }
}

OUTPUT :

Yes found.. and the correspoding key is ID and the employee is Smith

5 Comments

Guess I'ma just have to write my own function for it then huh?
Nope just do a foreach and you can do it inside of that.
I edited my post, look at the code and tell me if you think its right, or if there's a way to make it better.
@JacobCohen, See the edited answer are you looking something similar like this ?
Almost! I wanted to do it for a specific key I pick. I managed to write it on my own though, thanks for the muse.
8

First you must know which part of the associative array you're going to use as haystack in in_array function. Then you can use in_array without additional code.

Example with values :

<?php
$assoc = array(1 => "apple", 2 => "banana", 3 => "lemon", 4 => "pear");
$haystack = array_values($assoc);
echo "<p>" . print_r($assoc, true) . "</p>";

$needle = 'banana';
$find = (in_array($needle, $haystack)) ? 'TRUE' : 'FALSE';
echo "<p>$needle : $find</p>";

$needle = 'cherry';
$find = (in_array($needle, $haystack)) ? 'TRUE' : 'FALSE';
echo "<p>$needle : $find</p>";
?>

Results in :

Array ( [1] => apple [2] => banana [3] => lemon [4] => pear )

banana : TRUE

cherry : FALSE

Comments

4

Syntax

 in_array(mixed $needle, array $haystack, bool $strict = false): bool

Needle can be mixed type, so it can be any type, no issues if it is a numeric or associative array.

in_array('foo',array_unique(array_keys($array)));

Comments

0

The sample formule, using class and methods:

class VerifyInArray
{
 public function getMyCollection($field, $collection)
 {
     $list = array();
     if (count($collection)) {
        foreach ($collection as $k => $val) {
            $list[] = $val[$field];
        }
     }
     return $list;
 }

public function inMyArray($collection, $field, $findValue)
{
    if (isset($collection[0])) {
        if (array_key_exists($field, $collection[0]) == false) {
           return 'no'; 
        }
    }

    if (in_array($findValue, $this->getMyCollection($field, $collection))) {
        return 'ok';
    }
    return 'no';
}

public function displayInArray($collection, $attr, $value)
{
   return 'search result: '. $this->inMyArray($collection, $attr, $value);
}

}
$src = new VerifyInArray();

 $collection = array(
         array(
               'ID' => 1, 
               'name' => 'Smith'
         ), 
         array(
               'ID' => 2, 
               'name' => 'John'
         )
    );
echo $src->displayInArray($collection, 'ID', 2). "\n<br>" .
     $src->displayInArray($collection, 'ID', 0);

Model in ideone

Comments

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.