Junaid afzal Junaid afzal - 6 months ago 27
PHP Question

Get only Numeric values from Array in PHP

I have an array that looks something like this:

Array (
[0] => Array ( [country_percentage] => 5 %North America )
[1] => Array ( [country_percentage] => 0 %Latin America )
)


I want only numeric values from above array. I want my final array like this

Array (
[0] => Array ( [country_percentage] => 5)
[1] => Array ( [country_percentage] => 0)
)


How I achieve this using PHP?? Thanks in advance...

Answer

You can use array_walk_recursive to do away with the loop,
passing the first parameter of the callback as a reference to modify the initial array value.
Then just apply either filter_var or intval as already mentioned the other answers.

$array = [
    ["country_percentage" => "5 %North America"],
    ["country_percentage" => "0 %Latin America"]
];

array_walk_recursive($array, function(&$value,$key){
    $value = filter_var($value,FILTER_SANITIZE_NUMBER_INT);
    // or 
    $value = intval($value);
});

print_r($array);

Will output

Array
(
    [0] => Array
        (
            [country_percentage] => 5
        )

    [1] => Array
        (
            [country_percentage] => 0
        )

)
Comments