Jump to content

[SOLVED] Select and Display Random Elements from Array


Omzy

Recommended Posts

Lets say I have a multi-dimensional array, as such:

 

 
$cats=array(
'flowers'=>array('Flowers', 'Flower Decorations'),
'balloons'=>array( 'Balloons', 'Balloon Decorations'),
'banners'=>array('Banners', 'Banner Decorations'),
'fruit-displays'=>array('Fruit Displays', 'Fruit Display Decorations'),
'ice-sculptures'=>array('Ice Sculptures', 'Ice Sculpture Decorations'),
);

 

And currently I'm displaying this data like this:

 

foreach($cats as $index => $value)
{
echo '<p><a href="/directory/'.$index.'/">'.$value[0].'</a> - '.$value[1].'</p>';
}

 

So this just displays all the array elements in the order they are in the array. But I now need some code that will select and display any 3 elements from this array.

 

I know I can use the shuffle() function to randomize the array but this means I lose my array indexes. Surely there is a simple way of doing this, I like to have minimal code and prefer to use PHPs in-built functions to accomplish simple tasks, rather than having to code a whole new function that does the same thing :-)

Link to comment
Share on other sites

Take a look at array_rand()

 

It will take the array anda  number of keys to take from the array

 

php.net's example;

 

<?php
srand((float) microtime() * 10000000);
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>

Link to comment
Share on other sites

Have you tried it? as I beg to differ

 

$cats=array(
'flowers'=>array('Flowers', 'Flower Decorations'),
'balloons'=>array( 'Balloons', 'Balloon Decorations'),
'banners'=>array('Banners', 'Banner Decorations'),
'fruit-displays'=>array('Fruit Displays', 'Fruit Display Decorations'),
'ice-sculptures'=>array('Ice Sculptures', 'Ice Sculpture Decorations'),
);

$rand_keys = array_rand($cats, 3);

foreach($rand_keys as $value)
{
echo '<p><a href="/directory/'.$value.'/">'.$cats[$value][0].'</a> - '.$cats[$value][1].'</p>';
}

Link to comment
Share on other sites

  • 1 month later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.