niggles
niggles

Reputation: 1034

PHP How do I properly check if an array is multi-dimensional - strange array behavior

If I have this array:

$foo[0] = 'bar';
$foo[1] = 'bar bar';

echo $foo[0][1];

// result
a
// i.e the second letter of 'bar'

I want to check that $foo[0][1] is not set i.e if I had:

$foo[0][1] = 'bar';

it would evaluate to true, but in my original example of $foo[0] = 'bar' I would expect that:

isset($foo[0][1])

would return false;

What's the correct way to test that please.

Upvotes: 2

Views: 2556

Answers (4)

Hamid Sarfraz
Hamid Sarfraz

Reputation: 1135

By using $foo[0][1], you are actually accessing the first character of the string $foo[0].

Upvotes: 0

cletus
cletus

Reputation: 625267

PHP doesn't have multidimensional arrays. It has arrays of arrays. It's important to understand the difference.

You need to do:

if (is_array($foo[0]) && isset($foo[0][1])) {
  ...
}

Upvotes: 7

Your Common Sense
Your Common Sense

Reputation: 157918

if (is_array($foo[0]));

and http://php.net/manual/en/language.types.string.php#language.types.string.substr for reference on returning "a";

Upvotes: 0

niggles
niggles

Reputation: 1034

doh

it's ->

array_key_exists($foo[0][1]);

I'm still confused as to why PHP thinks the $foo[0][1] is set though...

Upvotes: 0

Related Questions