Extract random elements from an array in php

1

Hi, I would like some help or explanation on how to extract more than one result from an array in a random way using php. Until the moment and achieved this code:

<?php
$N = mt_rand(2,4);
$ele = array('#instagood','#love','#beautiful','#me','#follow','#cute','#photooftheday','#followme','#tagforlikes','#happy','#food','#selfie','#like','#summer','
#picoftheday','#igers','#tbt','#friends','#fun','#fashion','#instadaily','#instalike','#follow4follow','#amazing','#music','#instamood','#nofilter','#nature','#life','#girls');
$cla = array_rand($ele, $N);
foreach($cla as $clave)
{
    $emojis = str_pad($ele[$clave], 30);
    echo $emojis;
}
?> 

This example works well. but when you put the code in this way:

<?php
$N = mt_rand(2,4);
$ele = array('#instagood','#love','#beautiful','#me','#follow','#cute','#photooftheday','#followme','#tagforlikes','#happy','#food','#selfie','#like','#summer','
#picoftheday','#igers','#tbt','#friends','#fun','#fashion','#instadaily','#instalike','#follow4follow','#amazing','#music','#instamood','#nofilter','#nature','#life','#girls');
$cla = array_rand($ele, $N);
foreach($cla as $clave)
{
    $emojis = str_pad($ele[$clave], 30);

}

echo $emojis;
?> 

It does not give the same results and unfortunately I need it that way to meet the value of another variable. If you can give me a solution or another way to extract more than one random element from an array, I thank you. Saludes ..

    
asked by BotXtrem Solutions 12.01.2018 в 21:02
source

1 answer

2

Place a counter and convert the variable that stores your data into an array in this way:

$N = mt_rand(2,4);
$ele = array('#instagood','#love','#beautiful','#me','#follow','#cute','#photooftheday','#followme','#tagforlikes','#happy','#food','#selfie','#like','#summer','
#picoftheday','#igers','#tbt','#friends','#fun','#fashion','#instadaily','#instalike','#follow4follow','#amazing','#music','#instamood','#nofilter','#nature','#life','#girls');
$cla = array_rand($ele, $N);
$i=0;
foreach($cla as $clave)
{
    $emojis[$i] = str_pad($ele[$clave], 30);
$i++;
}

var_dump($emojis); //muestra todos los valores que necesitas
    
answered by 12.01.2018 / 21:20
source