<?php
$arr = [1,1,2,4,3,1,1,0,1,5,8,9,1,1,2];
$direction = null;
$counter = 0;
foreach($arr as $idx => $val)
{
if(!isset($arr[$idx-1]))
{
continue;
}
if($val > $arr[$idx-1])
{
if($direction != 'incr')
{
$direction = 'incr';
$counter++;
}
}
elseif($val < $arr[$idx-1])
{
if($direction != 'decr')
{
$direction = 'decr';
$counter++;
}
}
else
{
$direction = null;
}
}
var_dump($counter); //int(6)
$arr = [1, 1, 2, 4, 3, 1, 1, 0, 1, 5, 8, 9, 1, 1, 2];
$direction = null;
$last = null;
$countMonotony = array_reduce(
$arr,
function ($total, $item) use (&$direction, &$last) {
if (is_numeric($last)) {
if ($item > $last && $direction != 'up') {
$total++;
$direction = 'up';
} elseif ($item < $last && $direction != 'down') {
$total++;
$direction = 'down';
} elseif ($item == $last) {
$direction = null;
}
}
$last = $item;
return $total;
}
);
var_dump($countMonotony); // int(6)