5

Let's says I have this array :

$numbers = array(1,2,3,4,5);

And this array :

$letters = array('A','B','C');

I want to put $letters entries inside $numbers randomly. I don't care about the order of $letters, but I want $numbersto keep the order. The goal is to have this kind of array :

$randomLettersInNumbers = array(1, 'B', 2, 3, 'A', 4, 'C', 5);

How can I achieve this ?

lepix
  • 4,992
  • 6
  • 40
  • 53
  • Huh... No :/ Sorry, does my question is too large... ? I believe I have to use array_splice but all my attempts end with a completely huge and incomprehensible function (which doesn't work). – lepix Mar 03 '12 at 00:39
  • possible duplicate of http://stackoverflow.com/questions/4376220/how-to-combine-two-arrays-randomly-in-php and http://stackoverflow.com/questions/6377433/join-two-php-arrays-randomly – Nir Alfasi Mar 03 '12 at 00:48
  • seems like PHP doesn't have an arbitrary insert function for an array, which makes it a mess to write. in python it's as easy as: `[numbers.insert(random.randint(0, len(numbers) - 1), letter) for letter in letters]` – Not_a_Golfer Mar 03 '12 at 00:49
  • 2
    @alfasin no duplicate. One array should remain in order versus one being randomized and randomly inserted. That's quite a difference to the referenced questions. As is the possible solution. – Samuel Herzog Mar 03 '12 at 00:58
  • 1
    @SamuelHerzog good argument :) – Nir Alfasi Mar 03 '12 at 01:10

1 Answers1

13
foreach($letters as $letter)
{
    array_splice($numbers, rand(0, count($numbers)), 0, $letter);
}
print_r($numbers);
Aaron W.
  • 9,254
  • 2
  • 34
  • 45
  • If you are using class objects and you want to insert just one item you still have to provide it as an **array with one element**, otherwise it will be forcefully cast to an array (each property will be a key). – StockBreak Jun 18 '20 at 07:47