Very basic - if value is in an array


just getting to grips with PHP at the moment, but stumbled across this little bump in my path.

I have an array:

    [int_array1] => Array
            [0] => HHH
            [1] => GGG
            [2] => FFF
            [3] => EEE
            [4] =>CCC
            [5] =>BBB
            [6] => AAA
            [7] => E999
            [8] => E999

    [int_array2] => Array
            [0] => GGGG
            [1] => FFFF
            [2] => EEE
            [3] => DDD
            [4] => CCC
            [5] => BBB
            [6] =>AAA
            [7] => E999
            [8] => E999

My question is, how can I check if "int_array2" is within the main array called "main"??

For example, I've been messing with loads of different combination of this:

if (in_array(int_array1, $main)) {print "Found it";} else {print "No luck";}

That doesn't work.

Any help would be much appreciated!
Best regards,
Who is Participating?
Marcus BointonConnect With a Mentor Commented:
You need to look in the array keys, not the values, so you could either do:

if (in_array('int_array1', array_keys($main))) {print "Found it";} else {print "No luck";}

or a cleaner way:

if (array_key_exists('int_array1', $main)) {print "Found it";} else {print "No luck";}

You also need to quote string array index values or literal strings, otherwise you'll get warnings about undefined constants.
It's because you need to quote the int_array1 in the in_array functions, e.g.

if (in_array('int_array1', $main)) { print "Found it"; } else { print "No Luck"; }

The spacing of { } etc is irrelevant just the way I code, in you're case you need to quote int_array1 as it's a string.  Hopefully this should work.


It's worth mentioning that the first parameter of the in_array functions doesn't always have to be quoted, for example if your using number indexes etc.

You can read more about in_array here:


A little confused as to your intentions... Do you:

a) want to know if there is a key called "int_value2" in the array $main, or,
b) want to know if the array $main contains the same values as in int_value2

if it's a) the solution is simple, use array_key_exists:

if (array_key_exists('int_array1', $main)) {print "Found it";} else {print "No luck";}

ShelfieldCollege, your solution didn't work for me using PHP 4.3.10

Hope this helps,

noshankusAuthor Commented:
Thanks a million Squinky. Exactly what I was looking for!

Cheers =)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.