yurt Posted March 26, 2010 Share Posted March 26, 2010 Hi, Sorry for how fundamental this question is, but I have all of a few hours experience with PHP... It seems to me that the following should output each item from the $data array followed by the value from the $class array that corresponds to it. However, it only outputs the value from $class for the first item. <?php $data = "pepper, apple, orange"; $items = explode(",", $data); $class = array( "onion" => "veg", "pear" => "fruit", "apple" => "fruit", "pepper" => "veg", "orange" => "fruit"); $i = 0; while ($i < count($items)) { $current = $items[$i]; echo $current; echo $class[$current] . "<br />"; $i++; }; ?> $class[$current] only outputs a value the first time through the loop (i.e. I get "pepperveg apple orange") I assume I'm missing something quite basic here, but I'd expect the value of $class[$current] to change with each iteration and be output. Is there a reason I can't use the values from one array to reference the keys in another like this? I had the same problem with using foreach() to achieve this. Could someone enlighten me? My searches are getting me nowhere. Thanks. Yurt Quote Link to comment https://forums.phpfreaks.com/topic/196649-using-value-in-while-loop-as-array-key-new-php-user/ Share on other sites More sharing options...
mikesta707 Posted March 26, 2010 Share Posted March 26, 2010 its probably because your other "keys" have a preceding space before them. Try changing the line $data = "pepper, apple, orange"; to $data = "pepper,apple,orange"; you could also simply just put them into an array like $item = array("pepper", "apple", "orange"); and it should work Quote Link to comment https://forums.phpfreaks.com/topic/196649-using-value-in-while-loop-as-array-key-new-php-user/#findComment-1032467 Share on other sites More sharing options...
yurt Posted March 26, 2010 Author Share Posted March 26, 2010 The $data is coming from CSV input in the full script where I had the problem - thus the long-winded way of creating the array. Thanks for your help. Since I probably can't avoid people using spaces in the input, I assume the following would also solve it. $current = trim($items[$i]); Quote Link to comment https://forums.phpfreaks.com/topic/196649-using-value-in-while-loop-as-array-key-new-php-user/#findComment-1032474 Share on other sites More sharing options...
mikesta707 Posted March 26, 2010 Share Posted March 26, 2010 yes, that would also solve the problem. you could also use str_replace to remove all spaces from the $data variable, but that may have unwanted side effects (like changing the word apple pie to applepie) Quote Link to comment https://forums.phpfreaks.com/topic/196649-using-value-in-while-loop-as-array-key-new-php-user/#findComment-1032478 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.