0

How can I randomize the results on this code ?

I have an array with more than four items on it, but I will like to get four of them only but not in order, how do I suppose to do that ? It can be done using foreach(array_slice ??

$i = 0;
foreach(array_slice($items_array,0,4) as $item) {
$output .= 'Item ID:'.$item['id'];
$i++;
}

My array

a:6:{i:0;a:4:{s:5:"title";s:17:"Spedition";s:2:"id";s:11:"ZCXbgH1JDt4";s:3:"url";s:40:"embed/ZCXbgH1JDt4";s:5:"image";s:38:"transport";}i:1;a:4:{s:5:"title";s:77:"DC...... 
2
  • My Array doesnot looks like and array. Commented Jul 12, 2012 at 7:32
  • @subirkumarsao That is how ` array( 'url' => $url, 'idr' => $id, 'title' => $title )` is saved on the database Commented Jul 12, 2012 at 9:47

5 Answers 5

3
$output = array_rand($items_array, 4);

array_rand()

1
  • Do you mean replace the whole foreach thing with that ?, can you elaborate a bit more ? Commented Jul 12, 2012 at 4:00
0

Solved

$item = array_rand($items_array, 4); //get only four at random
$i=0;
while($i<=3) { // instead of 4 you set it at 3 because the counter starts at 0
$output = 'Item ID:'.$items_array[$item[$i]]['id'];             
$i++;
}
0

Perfect Way for Get Random Value From Array

$numbers = range(1, 20);

shuffle($numbers); //this function will shuffle the array value

foreach ($numbers as $number) {
    echo "$number ";
}
-1

A better and easy solution would be using array_rand

$array          =  array("foo", "bar", "hallo", "world");
$rand_keys  =  array_rand($array,1);
echo $array[$rand_keys];
0
-1

This should do it for you.

$i = 0;
foreach(array_rand($items_array, 4) as $item) {
  $output .= 'Item ID:'.$item['id'];
  $i++;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.