0

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

4 Answers 4

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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
)

Comments

1

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));

Comments

1

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))));

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.