-2

Say I have the following array:

$n[5] = "hello";
$n[10]= "goodbye";`

I would like to find out the highest index of this array. In Javascript, I could do $n.length - 1 which would return 10. In PHP, though, count($n) returns 2, which is the number of elements in the array.

So how to get the highest index of the array?

Ariel
  • 119
  • 1
  • 10

2 Answers2

2

Use max() and array_keys()

echo max(array_keys($n));

Output:-https://eval.in/997652

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
  • Thanks! If there is no way to do it with a single command, this will do. – Ariel May 01 '18 at 12:30
  • 1
    array_keys is 1 command, then max is 2. So this is 2 steps (in a single line), where Javascript does it in one: `[].length`. No hassle, just interesting difference for me between php and javascript. – Ariel May 01 '18 at 12:33
  • @Ariel then i can say that `$n.length` is one step and `-1` from it will second step. :):) – Alive to die - Anant May 01 '18 at 12:37
  • True. But usually this is going to be useful in a loop, in which case: `for (i = 0; i < n.length; i++)`.... so only 1 step ;-) – Ariel May 01 '18 at 12:39
1
$n = [];
$n[5] = "hello";
$n[10]= "goodbye";

// get the list of key
$keyList = array_keys($n);

// get the biggest key
$maxIndex = max($keyList);

echo $n[$maxIndex];

output

goodbye
Daniel1147
  • 151
  • 2
  • 5