Search code examples
phparraysassociative-array

How to select random value in an associate array in php


I have a data(Associate array) that I got from mysql database which looks like this

$data=[
    ["id"=>"1", "words"=>"words 1"],
    ["id"=>"2", "words"=>"words 2"],
    ["id"=>"3", "words"=>"words 3"],
    ["id"=>"4", "words"=>"words 4"],
    ["id"=>"5", "words"=>"words 5"],
    ["id"=>"6", "words"=>"words 6"],
    ["id"=>"7", "words"=>"words 7"],
    ["id"=>"8", "words"=>"words 8"],
    ["id"=>"9", "words"=>"words 9"],
    ["id"=>"10", "words"=>"words 10"]
];

Now I want to form a new array that contains only 3 random arrays from this array ($data) but i cant do it, the function i am using is not working

Below is my code

$count="3";
$rand = array_intersect_key($array, array_flip(array_rand($array, $count)))

I want the new array to look like this

$new_data=[
    ["id"=>"1", "words"=>"words 1"],
    ["id"=>"2", "words"=>"words 2"],
    ["id"=>"3", "words"=>"words 3"]
];

in which the arrays are selected at random not just 1, 2, 3.

Please how can i achieve this, what am i doing that is wrong


Solution

  • Actually your source data works exactly as you request -- Have you just made a typo with $data array and the reference value in $rand being $array when it should be $data?


    Try using array shuffle and then slice the array to only be X number long. Note with this method that the original outer array keys (numeric) will not be preserved, whereas with your original working version they are preserved.

    $count = 3; // how many array rows do you want to keep?
    $newData = $data; // source array.
    shuffle($newData);  // reorder the array. 
    $newData = array_slice($newData,0,$count); // cut off after $count elements.
    

    Please note that PHP shuffle is not suitable for any cryptographic randomness.

    PHP shuffle() Documentation

    PHP array_slice() Documentation