gsingh85 Posted September 12, 2014 Share Posted September 12, 2014 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. Quote Link to comment Share on other sites More sharing options...
Masna Posted September 12, 2014 Share Posted September 12, 2014 (edited) $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 September 12, 2014 by Masna Quote Link to comment Share on other sites More sharing options...
ginerjm Posted September 12, 2014 Share Posted September 12, 2014 When you echo out the value in the loop, be sure to echo out a space char as well. Quote Link to comment Share on other sites More sharing options...
gizmola Posted September 12, 2014 Share Posted September 12, 2014 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 ) Quote Link to comment Share on other sites More sharing options...
Psycho Posted September 12, 2014 Share Posted September 12, 2014 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 ) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.