Jump to content

Unable to collate all array values outside for each loop.


gsingh85

Recommended Posts

Please see the following code:

$colors = ["red hello","green this","blue lovely","yellow morning"];

foreach ($colors as $towns) {
    
  $hello = (explode(" ", $towns));

}

If I do print_r($hello[1]); within the loop I get all the values of index [1] in the browser although not sure why there are no spaces between the words:

 

HelloThisLovelyMorning

 

However if I do the same print outside the loop I only get this displaying in the browser:

 

Morning

 

That's no good to me because I want all the values with the index of [1] so I can use them anywhere I want. Any help would be much appreciated.

 

 

So you want a 2nd array?

 

$colors = array("red hello","green this","blue lovely","yellow morning");
$firstwords = array();
$lastwords = array();
foreach ($colors as $val) {
    list($firstwords[], $lastwords[]) = explode(' ', $val);
}

print_r($firstwords);
print_r($lastwords);
Output is:

Array
(
    [0] => red
    [1] => green
    [2] => blue
    [3] => yellow
)
Array
(
    [0] => hello
    [1] => this
    [2] => lovely
    [3] => morning
)

If the first word is unique in all values, I would just convert the array to use those as the index for each item to keep the association tightly coupled:

 

 

 

$colors = array("red hello","green this","blue lovely","yellow morning");
$newColors = array();
foreach($colors as $towns)
{
    list($id, $value) = explode(' ', $towns);
    $newColors[$id] = $value;
}
 
print_r($newColors);

 

Output

 

Array
(
    [red] => hello
    [green] => this
    [blue] => lovely
    [yellow] => morning
)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.