Skip to content
Advertisement

Is there a better way to get only numeric value in php array without using for loop

Here’s the an example of array that has non-numeric value.

$categoryRating = 

 array:3 [
  1 => 60.0
  2 => 50.0
  5 => "in-progress"
]

And the result should be:

array:3 [
  1 => 60.0
  2 => 50.0
]

Here’s my code:

array_filter($categoryRating[$category->id]

but the result is the same as unfiltered.

$category is just a collection where I assigned id as new key for the filtered result.

Advertisement

Answer

edit: I included the oneliner from Kevin:

$array = [1 => 60.0, 2 => 50.0, 5 => 'in-progress'];
$array = array_filter($array, 'is_numeric');
var_dump($array);

Have you tried something like:

array_filter($categoryRating, function($v, $k) {
    return is_numeric($v);
}, ARRAY_FILTER_USE_BOTH));

It should return an array with all numeric values in your input array, but I haven’t tested it. Maybe you just have to play around with the $callback function of array_filter.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement