Reputation: 18891
Say I have the following array:
$arr = array(
"number2"=>"valid",
"number13"=>"valid"
);
and I need to find if there is a key that exists with number*
.
For $arr
, this would be true. For the following array:
$arr2 = array(
"key"=>"foo",
"key2"=>"foo2"
);
this would return false.
Upvotes: 7
Views: 15098
Reputation: 1935
EPB and Dan Horrigan got it right, but from code cleanliness perspective, let me leave these here:
If you purely want to return true or false, you don't need an if statement; just return the result of the empty()
check on the result of preg_grep()
:
return !empty(preg_grep('/^number[\d]*/', array_keys($arr));
If you need to run an 'if' check, count()
or !empty()
will return truthy/falsy already, you don't need to double-check their value:
if ( count( preg_grep('/^number[\d]*/', array_keys( $arr )) ) ) {
// Action when it is true
} else {
// Action when it is false
}
I personally prefer empty()
over counting the result array elements, because type consistency:
if ( !empty( preg_grep('/^number[\d]*/', array_keys( $arr )) ) ) {
// Action when it is true
} else {
// Action when it is false
}
More on truthy/falsy, i.e. when a statement evaluates to true/false: https://www.php.net/manual/en/language.types.boolean.php
Upvotes: 0
Reputation: 4029
This one assumes number needs to be followed by an actual number (edit: or nothing at all), adjust the regular expression as necessary. For example, anything starting with 'number', you could use /^number/
.
if(count(preg_grep('/^number[\d]*/', array_keys($arr))) > 0)
{
return true;
}
else
{
return false;
}
Upvotes: 5
Reputation: 1295
Here is a simple function which will do what you want:
function preg_grep_key($pattern, $input) {
return preg_grep($pattern, array_keys($input));
}
// ----- Usage -----
$arr = array(
"number2"=>"valid",
"number13"=>"valid"
);
if (count(preg_grep_key('/^number/', $arr)) === 0) {
// Nope
} else {
// Yep
}
Upvotes: 0
Reputation: 443
Use regular expression.
foreach ($arr as $key => $value) {
// NOTE: check for the right format of the regular expression
if (preg_match("/^number([0-9]*)$", $key)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
}
Upvotes: 2