How can I check if the last position of the array has been filled?

5

How can I check if the last position of the array has been filled?

I tried the array_pop function but it seems to cut the array element, I just want to check if at the last position of array there is something ...

    
asked by anonymous 20.09.2016 / 21:06

3 answers

7

You can use the end() function to get the last element of the array and check whether it has value or not.

$arr = [1,2,3, null];

$ultimo = end($arr);

if($ultimo){
    echo 'tem valor: '. $ultimo;
}else{
    echo 'é vazio';
}
    
20.09.2016 / 21:17
5

I would do so:

$array = [1, 2, 3];

$end = end($array);

if ($end) {
    echo "A última posição é {$end}";
}

Note: The end function only works with arrays stored in variables, since it expects a parameter passed by reference.

If you have problems with this, the way I usually solve this is to create a function that serves as a wrapper to be able to circumvent this "problem" in PHP:

function last(array $array) {
   return end($array);
}

last([1, 2, 3, 4, 5]); // int(5)
    
20.09.2016 / 21:18
3

Another alternative is to get the index value, using count to get the total of elements and subtract by 1 :

$array = ['foo', 'bar', 'baz'];

if (($indice = count($array)) > 0) { // Se for um índice válido
    $ultimoValor = $array[$indice - 1];

    echo $ultimoValor;
}
    
20.09.2016 / 21:31