Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PHP in_array with associative array?

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;
    }
}
like image 449
Jacob Cohen Avatar asked Feb 16 '14 08:02

Jacob Cohen


People also ask

Does in_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.

How do you code an associative array in PHP?

Associative array will have their index as string so that you can establish a strong association between key and values. The associative arrays have names keys that is assigned to them. $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115"); Above, we can see key and value pairs in the array.

How do you check if a value exists in an associative array in PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

Which associative array is used to pass data to PHP?

The $_POST is an associative array of variables. These variables can be passed by using a web form using the post method or it can be an application that sends data by HTTP-Content type in the request.


1 Answers

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

isset($a[$key])
like image 160
Phil LaNasa Avatar answered Oct 03 '22 06:10

Phil LaNasa