2

hi i have three array like this

$arr1 = array(2,3,4,5);
$arr2 = array(1,2,3,4);
$arr3 = array();

i need a loop function to duplicate each of the value inside $arr2 with the value inside $arr1 so the end result should look like this:

$arr3= array(1,1,2,2,2,3,3,3,3,4,4,4,4,4,4);

i know that i need to do an array_push into the $arr3 with $arr2[i] by doing this

for($i=0;$i < count($arr2);$++){
 array_push($arr3,$arr2[$i]);
}

but i dont know the outer loop for iterating the array_push loop, what should i add to do the duplicating?

0

1 Answer 1

1

Solution 1: You need to apply a foreach() and for() loop

1.Iterate over the first array $arr1

2.Check that value with the same key of the first array exists or not in the second array

3.Apply a loop based on first array values

4.Assign same value repeatedly based on loop

foreach($arr1 as $key=>$arr){

  if(isset($arr2[$key])){

     for($i=0;$i<$arr;$i++){

      $arr3[] = $arr2[$key];

     }
  }
}

print_r($arr3);

Output:-https://eval.in/1005648

Solution 2: You can use array_merge() and array_fill()

foreach($arr1 as $key=>$arr){

  $arr3= array_merge($arr3,array_fill(count($arr3),$arr,$arr2[$key]));

}

echo "<pre/>";print_r($arr3);

Output:-https://eval.in/1005666

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

Comments

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.