kevinabraham kevinabraham - 6 months ago 8
PHP Question

How to compare last 2 elements of an array?

I have an array:

array:8 [▼
0 => array:1 [▼
"data" => "789"
]
1 => array:1 [▼
"data" => "800"
]
2 => array:1 [▼
"data" => "789"
]
3 => array:1 [▼
"data" => "787"
]
4 => array:1 [▼
"data" => "787"
]
5 => array:1 [▼
"data" => "787"
]
6 => array:1 [▼
"data" => "787"
]
7 => array:1 [▼
"data" => "787"
]
]


I need to take out the last 2 elements of the array and compare them. I tried using
$getLast2 = array_slice($chart_data, -2, 2, true);
to get the last 2.

array:2 [▼
6 => array:1 [▼
"data" => "787"
]
7 => array:1 [▼
"data" => "787"
]
]


Which then splits it. But Im not sure how to compare these 2 elements within this new array. As the last 2 elements which are now
6
and
7
could change as more data is added. I basically need to tell if the first element is great than, less than or equal to the second element.

Answer

You can use built in end() function and then prev():

if (end($chart_data) == prev($chart_data)) {
    echo 'Two last elements of an array are equal!';
}