Search code examples
phparrayssearchstrpos

search php array for string and return the key?


Possible Duplicate:
Simple PHP strpos function not working, why?

I'm trying to search a php array for a certain string in a value and return the key.. but having no luck so far. I'm not sure what I'm doing wrong, but here's what I've done so far..

My array (called options):

Array
(
    [0] => Blue^35cm^10
    [1] => Pink^35cm, 40cm, 50cm^10, 3, 5
    [1] => Green^35cm, 50cm^3, 2
)

I'm trying to find Pink in the following code and trying to return the key..

foreach ($options as $key => $value) :
    if (strpos($value,'Pink')) :
        echo $key;
    endif;
endforeach;

But it doesn't seem to be working? Any help would be great!


Solution

  • The strpos function returns the position as an integer, in your example, Pink would return as 0.

    You need to check that strpos comes back as anything other than false, like so:

    if (strpos($value, 'Pink') !== false)