Pick items with array prefixes

1

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

But I'd like to get only data that starts with my_* . Is there a more elegant way, or will I have to run array , get the first 3 characters, and compare with my_ ?

    
asked by anonymous 02.05.2015 / 04:21

2 answers

5

One of several approaches that can be used for this is to use the preg_grep to return the items that match a pattern, and to do so, enter the array keys with the 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

View demonstração

Another way to do this is to use the array_filter function to filter the keys in the array using the array_keys function, and in the callback / a>, 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

View demonstração

    
02.05.2015 / 04:33
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 that the first position of the key starts with my_ using strpos.

    
02.05.2015 / 15:07