Posts

Showing posts with the label element

PHP: Get last element of array

Often you need to get the last element of PHP array. This is easy to achieve with using count() function, wich counts all elements in array. Because PHP arrays are indexed from 0, you must remeber to get "count()-1" element of an array, not "count()" element: $exampleArray = array( 3,6,8,11,14 ); $lastElement = $array[ count($exampleArray) - 1]; echo $lastElement; // prints 14 This is the obvious way for some begginer developers. But more experienced developers will know, that there is a function defined especially for this purpose: echo end( $exampleArray ); // prints 14 Because this function will move internal array pointer to the end, you can reset it if you are currently iterating over this orray, for example: reset( $exampleArray ); // prints 14 If you are afraid about non set array, or set as other type than array, you can use function is_array() to check if this variable is defined as array. You can also get a last key of an array in several ways: echo ...

Get last element of an array in PHP

To get last element of an array just use end() function. First idea can by get a index at count()-1 but remember that php arrays are associative arrays, so you can grab last element just by number. $lastElement = end($array); As simple as you see. It works even if your indexes are strings like 'name','surname' etc.

Get random element from an array in PHP

This tutorial will show you how to get a random element from an array in PHP. We will use mt_rand function and count to determine minimal and maximal index of a array. Remeber that arrays are indexed from 0, so if you have a ten elements array, the elements have indexes from 0 to 9. So, we need a random number that will by at least 0 but smaller than 10. Wi will user mt_rand function te generate that number. Se example how to use count and mt_rand to get random element from an array: $array = array( 1,2,3,4,5 ); echo $array[mt_rand(0,count($array)-1)]; As you can see we have to substract 1 from the size of an array. Also we use faster and better function mt_rand, because rand is slower and less randomness.

How to add element to an array ?

If you want how to add or append element to a PHP array, see this code snippet: $somethings = array(); $somethings[] = "element"; // append as last element $somethings[4] = "other element"; $somethings['thekey'] = "some other element";