Mister Verleg
Mister Verleg

Reputation: 4293

Append an array to each entry of another array

I am trying to generate an array containing an array for each of the items

the code i tried:

$array = array(1,2,3,4,5,6,7,8,9,10 );
$array2 = array('how','are','you') ;

foreach( $array2 as $key => $value ){
    $value = $array2;
}

result of this code

array(3) {
  [0]=>
  string(3) "how"
  [1]=>
  string(3) "are"
  [2]=>
  string(3) "you"
}

The desired result is an array where each of the words contains the following values:

 how  = 1,2,3,4,5,6,7,8,9,10

 are  = 1,2,3,4,5,6,7,8,9,10

 you  = 1,2,3,4,5,6,7,8,9,10

Upvotes: 0

Views: 68

Answers (4)

LF-DevJourney
LF-DevJourney

Reputation: 28529

You can use array_combine, check the live demo.

<?php
$array = array(1,2,3,4,5,6,7,8,9,10 );
$array2 = array('how','are','you') ;
print_r(array_combine($array2, array_fill(0, count($array2), implode(',', $array))));

Upvotes: 1

Sahil Gulati
Sahil Gulati

Reputation: 15141

This is an alternative approach for achieving desired output. Here we are using array_fill and array_combine to get the desired output. With this array_fill(0, count($array2), $array); we are creating an array of values with $array to the count of $array2, Then we are using array_combine to make $array2 as keys $values as values.

Try this code snippet here

<?php
ini_set('display_errors', 1);

$array = array(1,2,3,4,5,6,7,8,9,10 );
$array2 = array('how','are','you') ;

$values=array_fill(0, count($array2), $array);//here we are creating an array with $array
print_r(array_combine($array2, $values));

Upvotes: 1

Saty
Saty

Reputation: 22532

Using implode() to make it string

$array = array(1,2,3,4,5,6,7,8,9,10 );
$array2 = array('how','are','you') ;
$arr = [];
foreach( $array2 as $key => $value ){
   $arr[$value] = implode(",",$array);// using implode 
}
print_r($arr);

OUTPUT

Array
(
    [how] => 1,2,3,4,5,6,7,8,9,10
    [are] => 1,2,3,4,5,6,7,8,9,10
    [you] => 1,2,3,4,5,6,7,8,9,10
)

Upvotes: 1

Chinito
Chinito

Reputation: 1175

assign the array of numbers in each words.

$array = array(1,2,3,4,5,6,7,8,9,10 );
$array2 = array('how','are','you') ;
$newArray = [];
foreach( $array2 as $key => $value ){
   $newArray[$value] = $array;
}

Upvotes: 1

Related Questions