Reputation: 3228
I have a specific key in array that I would like to get, however it is suffix by an incremental counter.
Array
(
[nombre] => Carlos
[apellido] => Delfino
[sum1] => Array
(
[0] => Apple
[1] => Banana
[2] => Liquor
)
[sum3] => Array
(
[0] => Grapes
)
)
I am planning to put the sum
keys (sum1 & sum3) on a new array. A foreach
is on my mind however I am doubting should I use regex or PHP string function for this.
foreach($arr as $k => $v)
{
//I'm lost here on how to match keys with at least `sum` word on it
}
Upvotes: 0
Views: 168
Reputation: 6767
This will check if it word begins with sum. If there are going to be other keys that being with sum and have non-integer values after them, a regexp would be needed.
foreach($arr as $k => $v)
{
if (strpos($k, 'sum') === 0) {
// key begins with 'sum'
}
}
Regexp way:
foreach($arr as $k => $v)
{
if (preg_match('/^sum[0-9]+$/', $k)) {
// key begins with 'sum' and is followed by an integer
}
}
Upvotes: 1