Home > Mobile >  use rand() number to echo array values
use rand() number to echo array values

Time:03-04

I am using rand() function to generate a random number. I want to echo array values based on this random number.

My code is as follows:

$total = rand(0,20);

In case the output is '3', i want to have three values echoed, i.e:

$listItems[0] . $listItems[1] . $listItems[2]

In case the output is '5', i want to have five values echoed, i.e:

$listItems[0] . $listItems[1] . $listItems[2] . $listItems[3] . $listItems[4]

Any ideas on how to achieve this please?

CodePudding user response:

or you could use a for loop

$total = rand(0,20);
for ($i=0;$i<=$total;$i  )
{
    echo $listItems[$i];
}

CodePudding user response:

As per @0stone0's comment. You can avoid a loop here and just use array_slice() and implode()

Note my example uses PHP 8's named parameters when using the array_slice() method

$total = rand(0, count($items)); // Get a random number between 0 and the number of items in the array
$reducedItems = array_slice($items, length: $total); // Reduce the items array to only contain the int stored in $total
echo implode($reducedItems); // Echo all the items left, will not exceed $total
  • Related