user2267801
user2267801

Reputation: 41

Remove random items from PHP array

I need to reduce the size of this array to X, so i would like to remove X random items. Here's my PHP array:

Array
(
    [helping] => 3
    [me] => 2
    [stay] => 1
    [organized!] => 1
    [votre] => 4
    [passion,] => 1
    [action,] => 1
    [et] => 2
    [impact!] => 1
    [being] => 4



)

I tried array_rand() but it didn't keep the keys/values.

Upvotes: 4

Views: 3188

Answers (5)

COil
COil

Reputation: 7606

If you need to remove an unknown item number, you can do :

$myArr = [
    'helping' => 3,
    'me' => 2,
    'stay' => 1,
    'organized!' => 1,
    'votre' => 4,
    'passion,' => 1,
    'action,' => 1,
    'et' => 2,
    'impact!' => 1,
    'being' => 4,
];
$countToRemove = random_int(1, 2); // can return 1 or 2
$keysToRemove = array_rand($myArr, $countToRemove); // returns an int or array
// create the array to loop
foreach (\is_array($keysToRemove) ? $keysToRemove : [$keysToRemove] as $key) { 
    unset($myArr[$key]);
}
var_dump($myArr); die();

In this case it will randomly remove 1 or 2 items from the array.

Upvotes: 0

Adrian
Adrian

Reputation: 1046

Use this,

$array = array(); // Your array

$max = 3;
$keys = array_rand($array, count($array) - $max);

// Loop through the generated keys
foreach ($keys as $key) {
    unset($array[$key]);
}

Upvotes: 0

quid
quid

Reputation: 1034

$foo = Array(
    "helping" => 3,
    "me" => 2,
    "stay" => 1,
    "organized!" => 1,
    "votre" => 4,
    "passion," => 1,
    "action," => 1,
    "et" => 2,
    "impact!" => 1,
    "being" => 4
);

$max = 5; //number of elements you wish to remain

for($i=0;$i<$max;$i++){ //looping through $max iterations, removing an element at random
     $rKey = array_rand($foo, 1);
     unset($foo[$rKey]);
}


die(print_r($foo));

Upvotes: 0

Marty McVry
Marty McVry

Reputation: 2856

array_rand() returns an array with keys from your original array.

You would need to delete the keys from your original array using a foreach-loop.

Like this:

// Suppose you need to delete 4 items.
$keys = array_rand($array, 4);

// Loop through the generated keys
foreach ($keys as $key) {
    unset($array[$key]);
}

Upvotes: 2

erenon
erenon

Reputation: 19118

array_rand() returns a random key (or more) of the given array, unset using that:

$randomKey = array_rand($array, 1);
unset($array[$randomKey]);

Upvotes: 3

Related Questions