mcmuney Posted February 16, 2011 Share Posted February 16, 2011 $color=array("01 orange","02 blue","03 red"); If my array was structured this way where the first two characters represented a code, how would I be able to display the code and color distinctly? Link to comment https://forums.phpfreaks.com/topic/227812-display-partial-array/ Share on other sites More sharing options...
jcbones Posted February 16, 2011 Share Posted February 16, 2011 foreach($color as $value) { $parts = explode(' ',$value); echo 'Code: ' . $parts[0] . '<br />Color: ' . $parts[1]; } Link to comment https://forums.phpfreaks.com/topic/227812-display-partial-array/#findComment-1174761 Share on other sites More sharing options...
mcmuney Posted February 16, 2011 Author Share Posted February 16, 2011 This almost works, but if I had a color "04 dark brown", the below would only show "dark" as the color and not "dark brown", is there a fix for that? foreach($color as $value) { $parts = explode(' ',$value); echo 'Code: ' . $parts[0] . '<br />Color: ' . $parts[1]; } Link to comment https://forums.phpfreaks.com/topic/227812-display-partial-array/#findComment-1174765 Share on other sites More sharing options...
Zurev Posted February 16, 2011 Share Posted February 16, 2011 This almost works, but if I had a color "04 dark brown", the below would only show "dark" as the color and not "dark brown", is there a fix for that? foreach($color as $value) { $parts = explode(' ',$value); echo 'Code: ' . $parts[0] . '<br />Color: ' . $parts[1]; } That's a bit, um, inefficient? Store it as an associative array: $color = array( "01" => "Orange", "02" => "Blue", "03" => "Red", "04" => "Dark Brown" ); // To display them.... foreach ($color as $key => $val) { // $key represents the code // $val represents the color echo "Code/Color: ".$key."-".$val."<br />"; } Link to comment https://forums.phpfreaks.com/topic/227812-display-partial-array/#findComment-1174771 Share on other sites More sharing options...
jcbones Posted February 16, 2011 Share Posted February 16, 2011 If you MUST do it the first way, change this line to: $parts = explode(' ',$value,2); It should fix that problem. Link to comment https://forums.phpfreaks.com/topic/227812-display-partial-array/#findComment-1174773 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.