How to merge multiple arrays outside of their loops? - php

I am trying to create an array from 2 other arrays. I am having a problem getting them merged outside of their loops.
Here is the code to build the 2 arrays:
$redDogs = '3';
$blueDogs = '2';
$i = 1;
// build red dogs array
$redDogs = (int)$redDogs;
while($i <= $redDogs) {
$reds[] = 'red_dog_' . $i++;
}
foreach ($reds as $red) {
print '<pre>'; print_r($red); print '</pre>';
}
$j = 1;
// build blue dogs array
$blueDogs = (int)$blueDogs;
while($j <= $blueDogs) {
$blues[] = 'blue_dog_' . $j++;
}
foreach ($blues as $blue) {
print '<pre>'; print_r($blue); print '</pre>';
}
How could I create an array like:
print_r($alldogs);
To produce the following output:
Array {
[0] => red_dog_1
[1] => red_dog_2
[2] => red_dog_3
[3] => blue_dog_1
[4] => blue_dog_2
}
I have tried array_merge($red, $blue) but don't seem to get any values.
Any help is greatly appreciated.

$redDogs = '3';
$blueDogs = '2';
$i = 1;
// build red dogs array
$redDogs = (int)$redDogs;
while($i <= $redDogs) {
$reds[] = 'red_dog_' . $i++;
}
$j = 1;
// build blue dogs array
$blueDogs = (int)$blueDogs;
while($j <= $blueDogs) {
$blues[] = 'blue_dog_' . $j++;
}
print_r(array_merge($reds, $blues));
Merge your array before looping through the array.
Your foreach statements were converting your array to strings.

Related

How to add string into array in PHP?

I have these for loop to determine consecutive number. What I achieve so far is to print the output in string.
$arr = [1,2,3,6,11,5,4,8,9,3];
for($start=0; $start<=count($arr); $start++){
for($end=$start+1; $end<=count($arr); $end++){
$total = $arr[$end] - $arr[$start];
if($total == 1){
echo 'Number is '.$arr[$start].','.$arr[$end].'<br/>';
} else {
echo '';
}
$arr[$start++];
}
}
My goal is to add the output into array.
I tried to use multidimensional array but no output display.
$arr = [1,2,3,6,11,5,4,8,9,3];
$arr3 = [];
for($start=0; $start<=count($arr); $start++){
for($end=$start+1; $end<=count($arr); $end++){
$total = $arr[$end] - $arr[$start];
if($total == 1){
$arr2 = array();
$arr2[] = $arr[$start].','.$arr[$end].'';
$arr3[] = $arr2;
} else {
}
$arr[$start++];
}
}
echo '<pre>';
print_r($arr3);
echo '</pre>';
exit;
Appreciate if someone can help me. Thanks.
you can simply use array functions, if sorting is important to you as #nice_dev said, you must sort your array before.
$arr = [1,2,3,6,11,5,4,8,9,3];
$cons = [] ;
while (array_key_last($arr) != key($arr)) {
if ((current($arr)+1) == next($arr)) {
prev($arr);
$cons[] = current($arr) . ',' . next($arr);
}
}
print_r($cons);
the output will be :
Array
(
[0] => 1,2
[1] => 2,3
[2] => 8,9
)
You can better sort() the input array first. This way, collecting all consecutive elements would get much simpler. If value at any index isn't +1 of the previous one, we add the $temp in our $results array and start a new $temp from this index.
Snippet:
<?php
$arr = [1,2,3,6,11,5,4,8,9,3];
$result = [];
sort($arr);
$temp = [];
for($i = 0; $i < count($arr); ++$i){
if($i > 0 && $arr[ $i ] !== $arr[$i - 1] + 1){
$result[] = implode(",", $temp);
$temp = [];
}
$temp[] = $arr[$i];
if($i === count($arr) - 1) $result[] = implode(",", $temp);
}
print_r($result);
Online Demo

How do I loop two array as one in PHP

I have a probrem but I don't know how to fix it,
here is two array
first is$X = A,B,C,D
second likes this a[1]a[2]a[3]a[4]a[5]a[6]a[7]a[8]
I want to loop likes this
Aa[1]a[2]
Ba[3]a[4]
Ca[5]a[6]
Da[7]a[8]
now i write likes this
foreach($X as $key) {
for ($i = 0; $i < 8; $i++) {
$a[$i];
}
$g=$a[$key][$i];
}
But it isn't that thing I want.
how can I fix it? thank you for your help.
You can try for
<?php
$X = ['A','B','C','D'];
$Y = ['a[1]a[2]','a[3]a[4]','a[5]a[6]','a[7]a[8]'];
$result = [];
for ($i=0; $i < sizeof($X) ; $i++) {
$result[] = $X[$i].$Y[$i];
}
?>
Output
Array
(
[0] => Aa[1]a[2]
[1] => Ba[3]a[4]
[2] => Ca[5]a[6]
[3] => Da[7]a[8]
)

PHP endless loop, why?

Here is my code. I don't understand why am I in endless loop.
I think $check has to stop the loop when I make unique random values for my array.
<?php
$foo["blue"] = 0;
$foo["black"] = 0;
$foo["red"] = 0;
$foo["white"] = 0;
$check;
do
{
foreach($foo as &$val)
{
$val = rand(1,6);
}
$foo = array_unique($foo);
$check = count($foo);
}
while($check != 4);
echo '............................ <br>';
foreach($foo as $key=>$value)
{
echo $key . ' ' . $value . '<br>';
}
?>
The problem is that the first time through the loop there are some duplicates, so array_unique() reduces the array from 4 elements to 1, 2, or 3. The foreach loop can never make the array bigger again, because it's only looping over the elements that currently exist in the array. So once the array shrinks, it will never grow back to 4 elements, and $check != 4 will always be true.
You should get the original keys of the array and use that.
<?php
$foo["blue"] = 0;
$foo["black"] = 0;
$foo["red"] = 0;
$foo["white"] = 0;
$keys = array_keys($foo);
$check;
do
{
foreach($keys as $i)
{
$foo[$i] = rand(1,6);
}
$foo = array_unique($foo);
$check = count($foo);
}
while($check != 4);
echo '............................ <br>';
foreach($foo as $key=>$value)
{
echo $key . ' ' . $value . '<br>';
}
?>
DEMO
Personally, I wouldn't do it in a loop with such low entropy as it could take all day to finally match a random set.
A better way would be to generate a range and randomise that, then loop over your array and set the value.
<?php
$rand = range(1, 6);
shuffle($rand);
$foo["blue"] = 0;
$foo["black"] = 0;
$foo["red"] = 0;
$foo["white"] = 0;
$i=0;
foreach ($foo as $key => $value) {
$foo[$key] = $rand[$i];
$i++;
}
print_r($foo);
/*Array
(
[blue] => 1
[black] => 3
[red] => 2
[white] => 5
)
*/
https://3v4l.org/4hPku

PHP Shouldnot Repeat and should be from an array

I'm trying to build a script that does two thing.
1) The Numbers should not repeat.
2) The numbers should be from an array called $id.
<?php
$a = array(); // final array which will have our id's to display
$id = array(1, 3, 5, 7, 9); //final array should contain a number only from this list
$itemstoshow = 3; // how many items to display
for($i = 0; $i < $itemstoshow; $i++) {
do {
$a[$i] = assignid(9);
$chkid = checkeer($a[$i], $i);
$chkdata = chkdata($a[$i], $i);
} while($chkdata == "nonexist" or $chkid == "repeatedid");
}
// display numbers in the array
for($i = 0; $i < $itemstoshow; $i++) {
echo "Item " . $a[$i] . "--------";
}
// check for redundancy function
function checkeer($x, $y)
{ //first parameter is query aray second is counter
global $a;
$err = 0;
// check if repeating number
for($i = 0; $i <= $y - 1; $i++) {
if($x == $a[$i]) {
$err = 1;
}
}
if($err == 1) {
return "repeatedid";
}
}
//check if array $a holds value from $id or not
function chkdata($x, $y)
{
global $a;
global $id;
for($i = 0; $i <= $y - 1; $i++) {
if($x !== $id[$i]) {
return "nonexist";
}
}
}
//assign id function
function assignid($x)
{
return rand(1, $x);
}
problem number 1 solved problem number 2 still not solved please help me.
the code should show 3 numbers from 1 to 9 which donot repeat and are in the array $id
You could use a combination of array_rand and array_map to get random values from the array that has the values your basing the randomization. Take a look:
$id = array(1,3,5,7,9); //final array should contain a number only from this list
$itemstoshow = 3;
$values = array_map(function($item) use($id){
return $id[$item];
}, array_rand($id, $itemstoshow));
print_r($values);
Output:
Array
(
[0] => 1
[1] => 3
[2] => 9
)
Running again:
Array
(
[0] => 3
[1] => 7
[2] => 9
)
You can use array_rand that selects random keys:
$id = array(1,3,5,7,9);
$result = array_intersect_key($id, array_flip(array_rand($id, 3)));
Or you can shuffle the array and take for example the 3 first items:
$id = array(1,3,5,7,9);
$temp = $id;
shuffle($temp);
for ($i = 0; $i < 3; $i++) {
$result[] = $temp[$i];
}

PHP Pick random array values based on total

I have array in php like
$randomarray = array('1106'=>'5','1110'=>'2','11867'=>'3','1206'=>'2','1210'=>'1','1223'=>'6','1235'=>'3','12565'=>'4','1258'=>'5','12690'=>'2','12693'=>'3','1283'=>'1','12944'=>'5');
I want to randomly pick elements from the array with the count of exactly 20. Each element have to only one time
I tried some array random example. I can't able to get the exact total which i expect.
this is the example of what i did that. But loop went to infinitive,
function randomTo($numIn) {
global $randomarray;
$numOut = 0;
$numbers = array();
do {
$key = array_rand($randomarray );
$add = $mainarray[$key];
if($numOut + $add > $numIn)
continue;
$numOut += $add;
$numbers[] = $add;
unset($mainarray[$key]);
} while( $numOut != $numIn );
return $numbers;
}
$testdata = randomTo(20);
The problem that you're trying to solve is called Subset sum and it's a subset of the Knapsack problem.
Just google for it, and while you're at it, google for Dynamic programming as it's a way of approaching the problem.
if(count($randomarray)) > 20
print_r(array_rand($randomarray, 20));
Get some Idea from this :
An example for getting random value from arrays
$r = array();
for ($i = 0; $i < $num; $i++) {
$r[] = $arr[$i];
}
return $num == 1 ? $r[0] : $r;
}
$a = array("apple", "banana", "cherry");
print_r(array_random($a));
print_r(array_random($a, 2));
?>
cherry
Array
(
[0] => banana
[1] => apple
)
And example for getting random value from assoc arrays;
<?php
function array_random_assoc($arr, $num = 1) {
$keys = array_keys($arr);
shuffle($keys);
$r = array();
for ($i = 0; $i < $num; $i++) {
$r[$keys[$i]] = $arr[$keys[$i]];
}
return $r;
}
$a = array("a" => "apple", "b" => "banana", "c" => "cherry");
print_r(array_random_assoc($a));
print_r(array_random_assoc($a, 2));
?>
Array
(
[c] => cherry
)
Array
(
[a] => apple
[b] => banana
)

Categories