Irving Soto Guzman
Irving Soto Guzman

Reputation: 33

PHP get different random array elements

Actually I have this code to get differents elements depending of how many many values $N represents.

$my_array = array('a','b','c','d','e');
foreach( array_rand($my_array, $N) as $key )
{
  echo $my_array[$key];
}

For example if $N = 2, I will get two random elements and it works fine.

The problem is when $N = 1, I get the following error:

WARNING Invalid argument supplied for foreach()

Any idea or advice to fix it?

Upvotes: 0

Views: 56

Answers (3)

Balamurugan M
Balamurugan M

Reputation: 620

<?php
$my_array = array('a','b','c','d','e'); 
shuffle($my_array); 
if($my_array!=NULL)
{ 
    foreach($my_array as $data)
    { 
      echo $data;
    }
} 

Upvotes: 0

Hunman
Hunman

Reputation: 155

If array_rand's 2nd parameter is 1, it returns an element instead of an array containing the elements.

For example:

$my_array = array('a','b','c','d','e');
array_rand($my_array, 1); // returns 'b'
array_rand($my_array, 2); // returns ['b', 'd']

You could do this:

$randoms = array_rand($my_array, $N);
if ($N == 1) {
    $randoms = [$randoms];
}
foreach ($randoms as $key) {
    // ...
}

Upvotes: 0

u_mulder
u_mulder

Reputation: 54831

Quick fix is:

$my_array = array('a','b','c','d','e');
// Cast result of `array_rand` to type "array"
foreach((array)array_rand($my_array, $N) as $key)
{
    echo $my_array[$key];
}

Upvotes: 3

Related Questions