Returns an element from the last array in a multidimensional array in PHP

How to display an element from the last array dynamically in PHP. For instance:

Array ( [0] => Array ( [id] => 6 [user_id] => 8 [category_path] => Sport) [1] => Array ( [id] => 8 [user_id] => 8 [category_path] => Computers)) 

to return "id" from the last array

 8 

And for the next example

 Array ( [0] => Array ( [id] => 6 [user_id] => 8 [category_path] => Sport) [1] => Array ( [id] => 8 [user_id] => 5 [category_path] => Computers) [2] => Array ( [id] => 16 [user_id] => 45 [category_path] => Soft)) 

to return

  16 

Thanks!

+4
source share
2 answers

Try the following:

 function getLastId(&$array){ $tmp=end($array); return $tmp['id']; } 
+10
source

How about counting and accessing items as follows?

 $array[count($array)-1] # to get the last array item $array[count($array)-1]['id'] # to get the id of the last entry 
+2
source

Source: https://habr.com/ru/post/1369438/


All Articles