1

I have an output arrays like this..

array
'B5' => string 'user1' (length=5)
'B4' => string 'user1' (length=5)

array
'D3' => string 'user1' (length=5)
'D2' => string 'user1' (length=5)
'D1' => string 'user1' (length=5)

array
'A4' => string 'user1' (length=5)
'A2' => string 'user1' (length=5)

array
 'E3' => string 'user1' (length=5)
 'E2' => string 'user1' (length=5)
 'E1' => string 'user1' (length=5)

I would like to check if a particular item such as 'E1' exists in these arrays. How should I go about this?

0

2 Answers 2

1

Use array_key_exists() function.

Example:

$answer = array_key_exists('E1', $array_name);

Or, more simple:

$answer = isset($array_name['E1']);

Sidenote: discussion about the use of isset() vs array_key_exists(). Worth to read if you care the performance.

Sign up to request clarification or add additional context in comments.

6 Comments

array_key_exists() can be used for one dimension array... only
This will not work for the array provided in the question, this will work only for one dimension array
OP does not mention multi-dimensional arrays.
see title of the question~~~
Given array is a multi dimensional array
|
0

This will check array_key_exists recursively for multi demnsional aray

function array_key_exists_r($needle, $haystack)
{
    $result = array_key_exists($needle, $haystack);
    if ($result) return $result;
    foreach ($haystack as $v) {
        if (is_array($v)) {
            $result = array_key_exists_r($needle, $v);
        }
        if ($result) return $result;
    }
    return $result;
}

Ref: http://www.php.net/manual/en/function.array-key-exists.php#82890

3 Comments

is that function crated by yourself? if not please mention the source!
I think they both took it from the same source .. looking at the date the php.net own is older ...

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.