alessiow
alessiow

Reputation: 21

Create an array using two arrays in PHP

I want to create an array using two arrays. The first array contains Strings. The second array contains numbers. I want to create a third array such as for example:

1st array:
array:2 [▼
  0 => "Test"
  1 => "People"
]

2nd array:
array:2 [▼
  0 => "3"
  1 => "2"
]

3rd array:
array:5 [▼
  0 => "Test"
  1 => "Test"
  2 => "Test"
  3 => "People"
  4 => "People"

]

Can you help me?

Upvotes: 0

Views: 79

Answers (1)

Eugene Nagornichyh
Eugene Nagornichyh

Reputation: 26

Try this

$firstArray = [
    0 => 'Test',
    1 => 'People'
];
$secondArray = [
    0 => '3',
    1 => '2'
];
$thirdArray = [];
foreach ($secondArray as $key => $array) {
    for ($i = 1; $i <= (int)$array; $i++) {
        $thirdArray[] = $firstArray[$key];
    }
}
var_dump($thirdArray);

output

array(5) {
  [0]=>
  string(4) "Test"
  [1]=>
  string(4) "Test"
  [2]=>
  string(4) "Test"
  [3]=>
  string(6) "People"
  [4]=>
  string(6) "People"
}

Upvotes: 1

Related Questions