PHP Coding Tips

Showing posts with label size. Show all posts
Showing posts with label size. Show all posts

Friday, August 17, 2012

How to get size of an array in PHP (count elements) ?

To count elements and grab size of an array in php just use a count function:$elementsNumber = count( $array ); This will return a number of elements that are set in array

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.