note 45176 added to function.array-rand

From: Date: Sat, 28 Aug 2004 01:16:25 +0000
Subject: note 45176 added to function.array-rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-75470@lists.php.net to get a copy of this message
According to office at at universalmetropolis dot com I have to say that the example is wrong. <?php // retrieve one of the options at random from the array $teamcolours = $teamcolours[rand(0,count($teamcolours))]; ?> The count() function will return the number of items in the array, that's the last index + 1. So if there's 2 items in the array, count() will return 2 but the indices are 0 and 1. Now since rand(x,y) randomizes between x and y inclusively the index from the above example may be out of bounds. Thus you have to subtract 1 from the count: <?php // Get random item $teamcolours = $teamcolours[rand(0,count($teamcolours)-1)]; ?> ---- Manual Page -- http://www.php.net/manual/en/function.array-rand.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+45176 Delete -- http://master.php.net/manage/user-notes.php?action=delete+45176&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+45176&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#75470) next »