viperjts10 Posted January 27, 2011 Share Posted January 27, 2011 I'm testing out small bits of code for myself, and I'm trying to understand why this isn't coming out how I would imagine it to... I have my function which stores colors in an array from a text file, then I return back a random color from my array like so... function getColor() { $ball_color = explode("\n", file_get_contents('colors.txt')); // Takes file contents and stores them into an array. return $ball_color[array_rand($ball_color)]; } And now in the main program, I simply have this: $color = getColor(); switch($color) { Case "blue": // echo stuff break; Case "red": // echo stuff break; etc... } For some reason though, my switch statement always reads the default case, making me assume that the words "blue" "red" "green" etc... aren't matching up to what I have set the cases at. When I output what color is actually being read, it displays exactly as it should, so I don't understand why the case "red" isn't opening up when that color is chosen, or same with any of the other colors. Is there some small conflict I'm unaware of in this tiny practice code? Any help is appreciated, thanks. Quote Link to comment https://forums.phpfreaks.com/topic/225802-reading-from-text-file-and-then-using-a-switch-case-not-working-together/ Share on other sites More sharing options...
jcbones Posted January 27, 2011 Share Posted January 27, 2011 Try: $color = getColor(); switch(trim($color)) { Case "blue": // echo stuff break; Case "red": // echo stuff break; etc... } Quote Link to comment https://forums.phpfreaks.com/topic/225802-reading-from-text-file-and-then-using-a-switch-case-not-working-together/#findComment-1165758 Share on other sites More sharing options...
litebearer Posted January 27, 2011 Share Posted January 27, 2011 yep trim is the trick Quote Link to comment https://forums.phpfreaks.com/topic/225802-reading-from-text-file-and-then-using-a-switch-case-not-working-together/#findComment-1165763 Share on other sites More sharing options...
viperjts10 Posted January 27, 2011 Author Share Posted January 27, 2011 Thank you so much. I didn't think any white space would be added if I didn't add any in the txt document, but I guess I was wrong. I appreciate the help here, thanks! Quote Link to comment https://forums.phpfreaks.com/topic/225802-reading-from-text-file-and-then-using-a-switch-case-not-working-together/#findComment-1165776 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.