A Couple Little PHP Array Tricks
To delete an item from an array:
unset($array[$i]);
However, this will break a “for ($i=0; $i<count(); $i++)” loop. To maintain sequential indexes:
$array = array_values($array);
This will reset the indexes; beware, though, the items may not be in the same order afterwards.
To select a random item from an associative list:
$array = array(
"one"=>1,
"two"=>2,
"three"=>3
);
$keys = array_keys($array);
$index = $keys[rand()%count($keys)];
$random = $array[$index];
// or, more compactly:
$k = array_keys($array);
$random = $array[$k[rand()%count($k)]];
Subscribe via Email Alerts
Subscribe in an RSS reader
What is RSS?
Eternicode on Twitter
Leave a Comment