Rasmus Bidstrup Rasmus Bidstrup - 2 months ago 6
PHP Question

PHP array of Strings into int

I have an array with some string values

array(4) {
[0]=> array(2) { ["x"]=> string(13) "1475269218000" ["y"]=> string(1) "1" }
[1]=> array(2) { ["x"]=> string(13) "1475269222000" ["y"]=> string(1) "1" }
[2]=> array(2) { ["x"]=> string(13) "1475269231000" ["y"]=> string(1) "1" }
[3]=> array(2) { ["x"]=> string(13) "1475269241000" ["y"]=> string(1) "1" }
}


I need an output with only values as ints. So this would be the output.

[
[1475269218000,1],
[1475269222000,1],
[1475269231000,1]
[1475269241000,1]
]

Answer

Option 1:

$ar = [
    ['x' => '1475269218000', 'y' => '1'],
    ['x' => '1475269222000', 'y' => '1'],
    ['x' => '1475269231000', 'y' => '1'],
    ['x' => '1475269241000', 'y' => '1']
];

foreach($ar AS $key1 => $sub_ars) {
    foreach($sub_ars AS $key2 => $val) {
        $ar[$key1][$key2] = intval($val);
    }
}
var_dump($ar);

Option 2:

$ar = [
    ['x' => '1475269218000', 'y' => '1'],
    ['x' => '1475269222000', 'y' => '1'],
    ['x' => '1475269231000', 'y' => '1'],
    ['x' => '1475269241000', 'y' => '1']
];

function intvalRecursive($val)
{
    if(is_array($val)) {
        return array_map('intvalRecursive', $val);
    }
    return intval($val);
}

$ar = array_map('intvalRecursive', $ar);
var_dump($ar);

Option 3 (stripping keys):

$ar = [
    ['x' => '1475269218000', 'y' => '1'],
    ['x' => '1475269222000', 'y' => '1'],
    ['x' => '1475269231000', 'y' => '1'],
    ['x' => '1475269241000', 'y' => '1']
];

foreach($ar AS $key => $val) {
    $ar[$key] = array_values(array_map('intval', $val));
}
var_dump($ar);