Which destructive and non-destructive way to get the last element of an array?

Asked

Viewed 201 times

0

This question came up in a group, but you did not know of such information, you would know the answer?

3 answers

2

U m a f o r m ad e s t u t i v a̶ ̶d̶e̶ ̶o̶b̶t̶e̶r̶ ̶o̶ ̶u̶l̶t̶i̶m̶o̶ ̶e̶l̶e̶m̶e̶n̶t̶o̶ ̶d̶e̶ ̶u̶m̶ ̶a̶r̶r̶a̶y̶ ̶é̶ ̶u̶t̶i̶l̶i̶z̶a̶n̶d̶o̶ ̶a̶ ̶f̶u̶n̶ç̶ã̶o̶ ̶̶a̶r̶r̶a̶y̶_̶p̶o̶p̶(̶)̶̶ ̶q̶u̶e̶ ̶e̶x̶t̶r̶a̶i̶ ̶u̶m̶ ̶e̶l̶e̶m̶e̶n̶t̶o̶ ̶d̶o̶ ̶f̶i̶n̶a̶l̶ ̶d̶o̶ ̶a̶r̶r̶a̶y̶ ̶e̶ ̶r̶e̶t̶o̶r̶n̶a̶ ̶o̶ ̶e̶l̶e̶m̶e̶n̶t̶o̶ ̶e̶x̶t̶r̶a̶i̶d̶o̶ ̶o̶u̶ ̶̶N̶U̶L̶L̶̶ ̶c̶a̶s̶o̶ ̶o̶ ̶a̶r̶r̶a̶y̶ ̶s̶e̶j̶a̶ ̶v̶a̶z̶i̶o̶:̶ ̶

̶ ̶ ̶ ̶ ̶<̶?̶p̶h̶p̶
̶ ̶ ̶ ̶ ̶$̶a̶r̶r̶ ̶=̶ ̶[̶'̶S̶e̶g̶u̶n̶d̶a̶'̶,̶ ̶'̶T̶e̶r̶ç̶a̶'̶,̶ ̶'̶Q̶u̶a̶r̶t̶a̶'̶,̶ ̶'̶Q̶u̶i̶n̶t̶a̶'̶,̶ ̶'̶S̶e̶x̶t̶a̶'̶]̶;̶
̶ ̶ ̶ ̶ ̶$̶u̶l̶t̶i̶m̶o̶ ̶=̶ ̶a̶r̶r̶a̶y̶_̶p̶o̶p̶(̶$̶a̶r̶r̶)̶;̶
̶ ̶ ̶ ̶ ̶p̶r̶i̶n̶t̶_̶r̶(̶$̶a̶r̶r̶)̶;̶
̶ ̶ ̶ ̶ ̶p̶r̶i̶n̶t̶_̶r̶(̶$̶u̶l̶t̶i̶m̶o̶)̶;̶
̶

R e t o r n a n d : ̶

̶ ̶ ̶ ̶ ̶A̶r̶r̶a̶y̶
̶ ̶ ̶ ̶ ̶(̶
̶ ̶ ̶ ̶ ̶ ̶ ̶ ̶ ̶[̶0̶]̶ ̶=̶>̶ ̶S̶e̶g̶u̶n̶d̶a̶
̶ ̶ ̶ ̶ ̶ ̶ ̶ ̶ ̶[̶1̶]̶ ̶=̶>̶ ̶T̶e̶r̶ç̶a̶
̶ ̶ ̶ ̶ ̶ ̶ ̶ ̶ ̶[̶2̶]̶ ̶=̶>̶ ̶Q̶u̶a̶r̶t̶a̶
̶ ̶ ̶ ̶ ̶ ̶ ̶ ̶ ̶[̶3̶]̶ ̶=̶>̶ ̶Q̶u̶i̶n̶t̶a̶
̶ ̶ ̶ ̶ ̶)̶
̶ ̶ ̶ ̶ ̶S̶e̶x̶t̶a̶
̶

A non-destructive way of obtaining the last element of an array is manipulated its index through the function count() which returns the number of elements:

<?php
$arr = [];
$arr[1] = "índice 1";
$arr[2] = "índice 2";
$arr[0] = "índice 0";
print_r($arr[count($arr) - 1]);

Returning:

índice 2

Consideration of the function end().

The function end() is used to obtain in a non-destructive way the last element added to an array, but it is clear that this function will not return the highest index element in arrays whose indices are numerical always returning the last added element, example:

<?php
$arr = [];
$arr[1] = "índice 1";
$arr[2] = "índice 2";
$arr[0] = "índice 0";
print_r(end($a));

Returning:

índice 0

Consideration of the function array_pop().

A way destructive to obtain the last element added to an array. This function will not return and remove the highest index element in arrays whose indices are numerical always returning and removing the last added element, example:

<?php
$arr = [];
$arr[1] = "índice 1";
$arr[2] = "índice 2";
$arr[0] = "índice 0";
print_r(array_pop($arr));

Returning and removing:

índice 0

1

The non-destructive form is the end cited by the colleague of the other answer, or direct access by the last index, if it is a numerically indexed array - if it is not, it makes no sense to speak of "last". The destructive form is the array_splice.

Example:

$arr = [1,2,3,4];
$ultimo = end($arr);
var_dump($ultimo);
var_dump($arr);
$ultimo = array_splice($arr, -1, 1);
var_dump($ultimo[0]);
var_dump($arr);

See it working on ideone.

-1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.