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

Asked

Viewed 885 times

5

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

I tried the function array_pop but it seems she cuts the element of array, I just want to check if in the last position of array is there anything...

  • 4

    Your question is about Java, php, mysql, Asp or php? Consider editing your question, as it is a flashy one for negative votes, as it is not presented clearly. (remark: it was not I who negatively)

  • Sorry, I already changed, it’s in PHP

  • 1

    is there anything? Would it be checking whether the value is not null, false or 0? Because if it is "there", you would have to know the exact position, you could show what you have already done?

  • I’ll give a +1, because this is a doubt that sometimes the people who are starting have.

3 answers

7

You can use the function end() to take 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';
}
  • Aff, it was faster

  • 1

    @Wallacemaxters almost a minute apart :P ta eating dust.

  • was exactly what I wanted, thank you very much guys

  • @Viniciusaquino you can mark one of the answers as useful if solved the problem. I suggest mark the one of rray, since he answered first :D

5

I would do so:

$array = [1, 2, 3];

$end = end($array);

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

Note: The function end 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 by creating 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)
  • Thank you, that’s exactly what I wanted

3

Another alternative is to get the value per index, using the 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;
}
  • 1

    The problem with that code is that if the count return 0, the -1 will generate a "Undefined index". Moreover, the array may not be numerical (as a list of Python), which will generate more headaches. Of course, your example will work because the array was declared numerical. But perhaps, for safety, it was necessary to use array_values to reset with a isset.

  • @Wallacemaxters Thanks. :) I already got the code, see if it’s better now.

  • 1

    That works :D+1

Browser other questions tagged

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