-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?

0

2 Answers 2

2

Use max() and array_keys()

echo max(array_keys($n));

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! If there is no way to do it with a single command, this will do.
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 then i can say that $n.length is one step and -1 from it will second step. :):)
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 ;-)
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.