How can we figure out where aaray ends?

I have an array result similar to this example 1:

Array ( [0] =>15 [1] => 16 [2] => 17 [3] => 18 )

      

Example 2:

Array ([0] => 15 [1] => 16 [2] => 17 [3] => 18 [4] => 18)

The first array ends in array [3] The second array ends in array [4] How to calculate where the array ends Is there a function to calculate this

+2


a source to share


6 answers


(Directly copied from http://www.php.net/manual/en/function.count.php )

Depending on what you mean by "end",



<?php
$yourArray = array(1=>'a', 7=>'b', 5=>'c');

print count($yourArray); // prints 3

end($yourArray);
print key($yourArray); // prints 5

print max(array_keys($yourArray)); // prints 7
?> 

      

For a regular array, just use count($a) - 1

.

+5


a source


Use the count function:

count(myArray)

      



This will tell you how many elements you have in the array.

http://www.w3schools.com/php/func_array_count.asp

+2


a source


I think you are trying to count the number of elements in an array?

If so, it will be the count function. http://php.net/manual/en/function.count.php

+2


a source


Associative matrix / array with holes attribute:

$lastElement = end($array);
$lastKey     = key($array); // only after end(); has set the internal array pointer!

      

+2


a source


If you only want the last value of the array, you can simply use array_pop

$arr = array('a','b','c');
echo array_pop($arr); //get 'c'

      

For fun:

$a = range(1, 100000);
shuffle($a);
$ts = microtime(true);
echo end($a),"\n";
printf("End =%.6f\n", microtime(true) - $ts);


//$b = range(1, 100000)
//shuffle($b);
reset($a);
$ts = microtime(true);
echo array_pop($a),"\n";
printf("Array_Pop=%.6f\n", microtime(true) - $ts);

      

Result:

68875
End=0.000289
68875
Array_Pop=0.000053

      

+2


a source


If it's just a normal numerically indexed array, you can simply use count()

that gives you the number of elements in the array. Since arrays are zero-based by default, you need to subtract them to get the end item index:

$array = array(0 => 15, 1 => 16, 2 => 17, 3 => 18);
$index = count($array) - 1;
echo $array[$index];

      

+1


a source







All Articles