0

I have a single key value array which I would like to loop through and create a seperate array from if certain conditions are met.

For example:

array(
1 => value
2.1 => value
2.2 => value
2.3 => value
2.4 => value
3 => value
)

My variable / condition I want to check is if the item in the array starts with a specific number. For example, if my var = 2, how can I create:

array(  
2.1 => value
2.2 => value
2.3 => value
2.4 => value    
)
Alex Knopp
  • 907
  • 1
  • 10
  • 30

1 Answers1

1

Array filter will do exactly what you need, I just combined that with substr to check if the first char is a 2 and if it is it will return that in the array.

array_filter($array, function($k) { 
        return substr($k, 0, 1) == '2';
    }, ARRAY_FILTER_USE_KEY);

Alternatively if you don't want to one line it you can create a function like the following to do it:

/**
 * @param array $array
 * @return array
 */
function filterArray(array $array): array 
{
    $finalData = [];
    foreach($array as $key => $value) {
        if(substr($key,0,1) == '2') {
            $finalData[$key] = $value; 
        }
    }

    return $finalData;
}
Lulceltech
  • 1,662
  • 11
  • 22