I need to find out if a string exists within an array value, but isn't necessarily the actual array value.

$array = array(
       0 => 'blue', 
       1 => 'red', 
       2 => 'green', 
       3 => 'red'
);

$key = xxxxxx('gr', $array); // $key = 2;

Is there a built in way to do this with PHP

Comments

What do you mean with $key = 2? Do you want to find a certain value or a certain key?

Written by markus

Accepted Answer

You can use preg_grep for this purpose

<?php
$array = array(
       0 => 'blue', 
       1 => 'red', 
       2 => 'green', 
       3 => 'red'
);

//$key = xxxxxx('gr', $array); // $key = 2;
$result=preg_grep("/^gr.*/", $array);
print_r($result);
?>

DEMO

Written by Shakti Singh
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki