Picking up items with array prefixes

Asked

Viewed 178 times

1

I own a array thus: array('one' => 1, 'two' => 2, 'three' => 3, 'my_one' => 55, 'my_two' => 33).

But I’d like to take only the data that started with my_*. Is there some more elegant way, or I’ll have to rotate the array, take the first 3 characters, and compare with my_?

2 answers

5


One of the many approaches that can be used for this, is to use the function preg_grep to return items that match a pattern, and to do so, enter the keys of the array with the function array_keys:

$numeros = array('one' => 1, 'two' => 2, 'three' => 3, 'my_one' => 55, 'my_two' => 33);
$myNumeros = preg_grep('/^my_.*/', array_keys($numeros));

print_r($myNumeros); // [3] => my_one [4] => my_two

See demonstração

Another way to do this is to use the function array_filter to filter the keys of the array using the function array_keys, and in the callback, compare the value with strpos (or stripos for case-insensitive):

$numeros = array('one' => 1, 'two' => 2, 'three' => 3, 'my_one' => 55, 'my_two' => 33);

$myNumeros = array_filter(array_keys($numeros), function ($chave){
    return (strpos($chave, 'my_') !== false);
    });

print_r($myNumeros); // [3] => my_one [4] => my_two

See demonstração

  • 1

    I edited the regular expression because the question requires my_*, and not my*.

0

Another approach would be this:

<?php
    $arr = array('one' => 1, 'two' => 2, 'three' => 3, 'my_one' => 55, 'my_two' => 33);
    foreach($arr as $key => $value){
        if(strripos($key, 'my_') === 0){
            echo $key.'<br />'; 
        }
    }
?>

Scroll through all items and check if the first position of the key starts with my_ using strpos.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.