abraham foto abraham foto - 1 day ago 4
PHP Question

Array: I want a function that print array in not consecutive order

I have a function that returns an array, the array if full of values like 'up' and 'down'. what i want to print values where the two consecutive values are not the same. example: if the first value is up, and the second values also up, it should print only the first one, likewise for down. it should keep on printing if the consecutive are different. thus the output is expected to be up, down, up, down ?

$a_ret = [];

foreach ($o_response as $o_status) {
$a_ret[] = [
'value' => $o_status->values,
'timestamp' => $o_status->created_at
];
}

return $a_ret;

}

Answer

This code will put every last value you put in your return array in the $last variable. So down, up, up up, down, up, up, down will become down, up, down, up, down.

$a_ret = [];    

$last = null;
foreach ($o_response as $o_status) {
    if($last != $o_status->values) {
        $a_ret[] = [
            'value' => $o_status->values,
            'timestamp' => $o_status->created_at
        ];
        $last = $o_status->values;
    } else {
        // Add this else if you want up, up, up to become up, up.
        // See  kapil.dev  comment on this answer
        $last = null;
    }
}

return $a_ret;
Comments