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)]];

Leave a Comment

You need to enable javascript in order to use Simple CAPTCHA.
Security Code: