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?

Raptor
  • 53,206
  • 45
  • 230
  • 366
Dev
  • 489
  • 5
  • 14

2 Answers2

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.

Community
  • 1
  • 1
Raptor
  • 53,206
  • 45
  • 230
  • 366
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

Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
  • 2
    is that function crated by yourself? if not please mention the source! –  Feb 25 '13 at 10:05
  • No its from: http://stackoverflow.com/questions/2948948/array-key-exists-is-not-working –  Feb 25 '13 at 10:15
  • I think they both took it from the same source .. looking at the date the php.net own is older ... – Baba Feb 25 '13 at 10:22