Jump to content

Unable to collate all array values outside for each loop.


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.

 

 


$wanted_values = array();

foreach($colors as $towns){
$hello = explode(" ", $towns);
$wanted_values[] = $hello[1];
}

//now use $wanted_values however you want - [0] -> "hello", [1] -> "this", etc.

 

Edited by Masna

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
)
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.