Miguel Mas
Miguel Mas

Reputation: 545

PHP: new array from several arrays

I'm teaching myself PHP and I have the following question about arrays:

I have:

   $names = array('John', 'Alice', 'Tom');
    $cities = array('London', 'NY', 'Boston');
    $years = array('1999', '2010', '2012');
    $colors = array('red', 'blue', 'green'); 

I want to have a new array with these elements (three subarrays):

 John London 1999 red
 Alice NY 2010 blue
 Tom Boston 2012 green 

I'm doing

 $newArray = array($names,$cities, $years,$colors);

But this shows all the names, cities and so all together :( Please show me how to achieve this.

Thanks a lot!

Upvotes: 0

Views: 213

Answers (4)

Shyam
Shyam

Reputation: 300

To get output like this --

John London 1999 red

Alice NY 2010 blue

Tom Boston 2012 green

You have to do following

$result = array();
foreach($names as $key=>$value){
$result[]='<pre>'.$value.' '.$cities[$key].' '.$years[$key].''.$colors[$key].'</pre>';
}

Then implode the generated array

$output=implode('',$result);
echo $output;

Upvotes: 0

Or you can use "for"

$count = count($names);
$new_array = array();
for($i=0;$i < $count; $i++) {
        $new_array[] = array( $names[$i], $cities[$i], $years[$i],$colors[$i]);
}

Upvotes: 0

Dpolehonski
Dpolehonski

Reputation: 958

If You want the three list to be arrays with each value an element in a sub array, do this:

$names = array('John', 'Alice', 'Tom');
$cities = array('London', 'NY', 'Boston');
$years = array('1999', '2010', '2012');
$colors = array('red', 'blue', 'green'); 

$final_array = array();

foreach($names as $count => $name){
    array_push($final_array,array($name,$cities[$count],$years[$count],$colors[$count]));
}

var_export($final_array);

This gives an output of:

array (
  0 => 
  array (
    0 => 'John',
    1 => 'London',
    2 => '1999',
    3 => 'red',
  ),
  1 => 
  array (
    0 => 'Alice',
    1 => 'NY',
    2 => '2010',
    3 => 'blue',
  ),
  2 => 
  array (
    0 => 'Tom',
    1 => 'Boston',
    2 => '2012',
    3 => 'green',
  ),

If you want the result to be an array of strings use Mihai's answer.

Upvotes: 0

Mihai Iorga
Mihai Iorga

Reputation: 39704

Use foreach():

$newArray = array();

foreach($names as $num => $name){
    $newArray[] = $name." ".$cities[$num]." ".$years[$num]." ".$colors[$num];
}

var_export($newArray);

Codepad Example

Upvotes: 1

Related Questions