Reputation: 690
I'm searching an array for specific values and I was wondering if I can search to see the value contains what I'm searching for, not necessarily an exact match
so..
$a = array("red", "reddish", "re", "red diamond");
this will only give me 1 key
$red = array_keys($a, "red");
what if I want all keys that contain the word red. so I want "red", "reddish" and "red diamond"
or rather I want 0, 1, 3
Upvotes: 0
Views: 104
Reputation: 10499
You can do this > Live Demonstration
Red
// Create a function to filter anything 'red'
function red($var) {
if(strpos($var, 'red') === false) {
// If array item does not contain red, filter it out by returning false
return false;
} else {
// If array item contains 'red', then keep the item
return $var;
}
}
// Set the array (as per your question)
$array = array("red", "reddish", "re", "red diamond");
// This line executes the function red() passing the array to it.
$newarray = array_filter($array, 'red');
// Dump the results
var_export( array_keys($newarray) );
Use of array_filter()
or array_map()
give the developer more control over fast loops through the array for filtering and executing other code. The function above is designed to do what you request, however it can be as complex as you want.
If you wish to set the value 'red' inside it to be more dynamic, you could do something like the following :
// Set the array (as per your question)
$array = array("red", "reddish", "re", "red diamond");
// Set the text you want to filter for
$color_filter = 'red';
// This line executes the function red() passing the array to it.
$newarray = array_filter($array, 'dofilter');
// Dump the results
var_export( array_keys($newarray) );
// Create a function to filter anything 'red'
function dofilter($var) {
global $color_filter;
if(strpos($var, $color_filter) === false) {
// If array item does not contain $color_filter (value), filter it out by returning false
return false;
} else {
// If array item contains $color_filter (value), then keep the item
return $var;
}
}
Upvotes: 1
Reputation: 4021
Use preg_grep
:
$a = array("red", "reddish", "re", "red diamond");
$red = array_keys(preg_grep("/red/", $a));
print_r($red);
The above code gives you the keys for all values in $a
that contain the string "red"
. If you need the keys for all values in $a
that begin with the string "red"
, simply change the regular expression from "/red/"
to "/^red/"
.
Upvotes: 1
Reputation: 487
$a = array("red", "reddish", "re", "red diamond");
function find_matches( $search, $array )
{
$keys = array();
foreach( $array as $key => $val )
{
if( strpos( $val, $search ) !== false )
$keys[] = $key;
}
return $keys;
}
Upvotes: 0