Pushing random array elements into another array in PHP - php

I have an array consisting of N>10 URLs. I want to randomly pick 10 of them and store them in another array. How can I achieve this? Is array_rand() the way to go? If yes, then how do I ensure that there are no duplicities in the output array? Do I have to check the second array everytime a new element is added for existence?
// $firstArray is defined earlier
$secondArray = array();
array_push(array_rand($firstArray, 10));
This doesn't work unfortunately. I was thinking about using a for cycle for the array_push() but I was just curious if array_rand() can do that for me.
Thanks for advice!

array_rand returns keys so
$randKeys = array_rand($firstArray, 10);
foreach($randKeys as $key)
$secondArray[] = $firstArray[$key]

This can be done without array_rand(). Use shuffle() to shuffle the array elements and then use array_slice() to get the first 10 items:
$secondArray = array();
shuffle($firstArray);
$secondArray = array_slice($firstArray, 0, 10);
Demo!

As people said there is a second argument in array_rand() to pick how many random elements you want, always remember to read the Manual
//Lets pick 10 mammals
$mammals = array('dog', 'cat', 'pig', 'horse', 'bat', 'mouse', 'platypus', 'bear', 'donkey', 'deer', 'hog', 'duck');
$ten = array_rand(array_flip($mammals), 10);
//If what yo u really wanted is to append them to another array, let's say "animals":
$animals = array('fish', 'crab', 'whale', 'eagle');
$animals = array_merge($animals, array_rand(array_flip($mammals), 10));
Explanation
array_rand() will return you the keys, so we can use array_flip() here to reverse the keys => values positions before picking them, no need to loop through them again.
And using array_merge() we merge them together, with no need to loop through the ten random elements to add them one by one, unless ... you want a specific order or other logic.

Not very optimized solution, but for small amounts of data it may suit:
$firstArray = array(1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9);
$secondArray = array();
$tmp = array_unique($firstArray);
shuffle($tmp);
$secondArray += array_slice($tmp,0, 10);

If you use array_push like in the example code, the last index in your second array will contain the returned 10 indexes
Eg.
$stack = array('a', 'b', 'c');
array_push($stack, array('d', 'e', 'f'));
print_r($stack);
Array (
[0] => a
[1] => b
[2] => c
[3] => Array (
[0] => d
[1] => e
[2] => f
)
)
I would use a while in this case and pick only one value at a time. Something like:
$stack = array();
while(count($stack)<10){
$item = array_rand($collection_of_urls);
if(!in_array($item)
array_push($stack, $item);
}

this simple
$rand_keys = array_rand($input, 10);
print_r($rand_keys);

Related

Combine dynamic arrays with dynamic keys in to single arrays

I have this dynamic multiple arrays that I need to combine in one array and serialized them. The problem is I need to keep both key and value.
$arr = array($bet_option_id => $bet_option_name);
Here i need to keep both bet_option_id AND bet_option_name. Then this result output:
Array ( [997650802] => Over 2.5 )
Array ( [997650807] => Yes )
This need to be simply
Array
(
[997650802] => Over 2.5
[997650807] => Yes
)
As it's dynamic, sometimes not comes with just single array so apparently I couldn't get it working. I need to retrieve both bet_option_id & bet_option_name. Tried something like this:
$arr = array($bet_option_id => $bet_option_name); //This is where all array keys, values are stores
$result = array();
foreach ($arr as $array) {
$result = array_merge($result, $array);
}
Any inputs will be nice.
Rather than create individual arrays like...
$arr = array($bet_option_id => $bet_option_name);
If you first create an empty array ( like you do with $result)
$arr = array();
and then add each item in using
$arr[$bet_option_id] = $bet_option_name;
Then you don't need to manipulate the array after - just create it as you want it in the first place.
You could either do like Nigel Ren suggested which is the most elegant solution
In case that you do not have arrays that their keys are entirely numeric you may use array_merge. The quote following is from PHP array-merge
Example #2 Simple array_merge() example
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
Don't forget that numeric keys will be renumbered!
Array
(
[0] => data
)
Alternatively you can always join arrays together like this
$a1 = [ 997650802 => 'Over 2.5' ];
$a2 = [ 997650807 => 'Yes' ];
var_dump( $a1 + $a2 ); // result is [997650802 => 'Over 2.5',997650807 => 'Yes']
You can check more about Array Types and Array Operators

How to cut array into two

I am trying to separate an array into two separate arrays. For example, if I have an array like this
Array([0]=>Hello[1]=>I'm[2]=>Cam)
I want to split it into two arrays and add another string
Array1([0]=>Hello[1]=>There,)
Array2([0]=>I'm[1]=>Cam)
Then finally add the two together
Array([0]=>Hello[1]=>There,[2]=>I'm[3]=>Cam)
What would be the simplest way to do this?
I know I can use array merge to put the two together but I don't know how to separate them at a certain point.
I'm also doing this on a large file that will be constantly getting bigger, so I cant use array_chunk()
Looking at your end result goal, I think a shorter method to get your desired response is to use array_splice which lets you insert into a middle of an array....
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$arrayVarExtra = array('There');
array_splice($arrayVarOriginal, 1, 0, $arrayVarExtra);
This should send you back Array([0]=>Hello[1]=>There,[2]=>Im[3]=>Cam) like you wanted!
The above avoids having to split up the array.
HOWEVER
If you did want to do it the hard way, here is how you would...
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$array1stPart = array(arrayVarOriginal[0], 'There');
$array2ndPart = array_shift($array1stPart);
$finalArray = array_merge($array1stPart, $array2ndPart);
How? array_shift removes the first item from any array, so that how we get $array2ndPart.... and $array1stPart is even easier as we can just manually build up a brand new array and take the first item from $arrayVarOriginal which is at position 0 and add 'There' in as our own new position 1.
Hope that helps :)
array_shift, array_splice, and array_merge are what you need to look into.
Based from your question, here step-by-step to get what you want for your final output.
1) Split Array
$arr = array('Hello', 'I\'m', 'Cam');
$slice = count($arr) - 1;
$arr1 = array_slice($arr, 0, -$slice);
$arr2 = array_slice($arr,1);
so, you get two new array here $arr1 and $arr2
2) Add new string
$arr1[] = "There";
3) Finally, combine the array
$arr = array_merge($arr1, $arr2)
Here sample output when you print_r the $arr
Array
(
[0] => Hello
[1] => There
[2] => I'm
[3] => Cam
)
array_slice second parameter is position where you want split. So you can do this dynamically by count the array length.
$string = array("Hello","I'm","Cam");
$firstArray = array_slice($string ,0,1);
array_push($firstArray,"There,");
$secondArray = array_slice($string ,1,2);
echo "<pre>";
print_r($firstArray);
echo "==========="."<pre>";
print_r($secondArray);
echo "<pre>";
print_r(array_merge($firstArray,$secondArray));
//out put
Array
(
[0] => Hello
[1] => There,
)
===========
Array
(
[0] => I'm
[1] => Cam
)
Array
(
[0] => Hello
[1] => There,
[2] => I'm
[3] => Cam
)
Hope it will be worked for your requirement. If not or you need more specify regarding this you can clarify your need.

PHP: how to add array index then cut into several array?

I have make many changes but still cannot figure out.
i have an array let say: [1,2,3,4,5,6,7,8,9,10]
i just want to ask how to add this array until index 2 and continued add for rest array then divide them by 2 array each.
input : [1,2,3,4,5,6,7,8,9,10 ];
process : [1+2+3, 4+5+6, 7+8+9, 10]
output i need : [6,15,24,10]
then i want to cut this array into 2
last output : [[6,5],[24,10]]
Thanks
Your code will be:
$data = range(1,10);
$result = array_chunk(array_map('array_sum', array_chunk($data, 3)), 2);
-please, read array functions manual
Something like this?
<?php
$array = range(1, 10);
$array = array_chunk($array, 3);
$array = array_map('array_sum', $array);
$array = array_chunk($array, 2);
print_r(
$array
);
/*
Array
(
[0] => Array
(
[0] => 6
[1] => 15
)
[1] => Array
(
[0] => 24
[1] => 10
)
)
*/
I think you can use a for cycle to sum what you need then store result in new array. Another solution is using array merge. When you've done the trick you can create a multidimensional array to get the result like [[6,5],[24,10]].
Hope it helps
Can't really see what you are getting at from the question, but I think PHP's array_chunk command may be your friend on this, http://www.php.net/manual/en/function.array-chunk.php
this will allow you to split the array into chunks of 3 (or any number) of elements with last element containing the remainder (in this case 1 element)

PHP 2 arrays - merge values existing in both arrays to one array

I have 2 arrays:
$array1 = array(1,2,3,4,5);
$array2 = array(3,4,5,6,7);
Is there any PHP function that does this?
$finalArray = unknown_php_function($array1,$array2);
// result: $finalArray = array(3,4,5);
It merges both arrays and removes values which aren't present in both arrays. Do I have to build a foreach cycle or is there an easier way? Thanks
You want array_intersect for this, basically the intersection of two sets (arrays, in this case), just like in school. :-)
You're looking for array_intersect(). Here is a demo:
$array1 = array(1,2,3,4,5);
$array2 = array(3,4,5,6,7);
$finalArray = array_intersect($array1,$array2);
print_r($finalArray);
Outputs:
Array
(
[2] => 3
[3] => 4
[4] => 5
)

Push the same element x times onto the array

Basically I need to create this array (given x = 3)
array('?','?','?');
I could do
for($i=0;$i<3;$i++)
$arr[]='?';
But it's not so elegant. Is there any other way?
Use array_fill( start_index, num, value ):
$arr = array_fill(0, 3, '?');
To address the question of how to push the same element a number of times onto an array, it's worth noting that while array_fill() is certainly the most elegant choice for generating a new array, this is the only thing it can do. It cannot actually push elements onto an existing array.
So while a basic loop isn't particularly exciting, it does work well in situations where you have an existing array you want to add to, regardless of whether it's already empty or not.
$arr = ['a', 'a', 'a'];
for ($i = 0; $i < 3; $i++) {
$arr[] = 'b';
}
print_r($arr);
Array
(
[0] => a
[1] => a
[2] => a
[3] => b
[4] => b
[5] => b
)
To achieve the same thing with array_fill() it requires an additional merge:
$arr = array_merge($arr, array_fill(0, 3, 'b'));

Categories