0

I m so confusing here with this problem, please help me to solve this.

I have 2 array data,

$one = array ("sinta","jojo","wawan","silvie");
$two = array ("eat","sleep","breakfast","sport");

I want to create a random output array from this 2 array, and i want this only pick 2 random array from each array data, so maybe the result would be like this :

$three = array ("sinta","silvie","breakfast","eat");

or

$three = array("jojo","silvie","eat","sleep"); 

and etc..

2 Answers 2

1

Normally I don't like code only answers, but:

$three = array_merge(array_rand($one, 2), array_rand($two, 2));
shuffle($three);

You can read up on array_rand and array_merge and shuffle in the linked manuals. This code picks 2 elements each from $one and $two at random, and then randomizes the order of the result.

Small warning: If you have string keys in your arrays they will be destroyed.

Sign up to request clarification or add additional context in comments.

7 Comments

thanks for answering,yess i want the array output result is something like you said array ('sinta','eat','sleep','silvie'), no the numeric keys only
Then you could shuffle the result. I'll edit my answer.
Sorry! The last edit was completely my mistake. I even linked the manual for shuffle, but used it wrong. I edited the code another time, and now it should be fine. Sorry again.
i try your syntax,but the output is 1,
The output from shuffle($three) should be 1 (TRUE) if the shuffle function was successful. What you need to do is print out the $three array after calling shuffle.
|
0
$three[0] = $one[rand(0,3)];
$three[1] = $one[rand(0,3)];
$three[2] = $two[rand(0,3)];
$three[3] = $two[rand(0,3)];

thats the logic - I did not php for a while so check the syntax, please. Now you have to assure that rand is not picking the same value twice or youhave to eat two breakfasts :-)

1 Comment

thank you for answering, but maybe this answer still not correct for me...

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.