G+_Matthew Reardon Posted January 13, 2015 Share Posted January 13, 2015 Coding 101 - PHP I can count! <?php $limit = $_GET["number"]; $count = 1; while ($count <= $limit) { echo "$count \n"; $count++; } ?> Link to comment Share on other sites More sharing options...
G+_Nate Follmer Posted January 13, 2015 Share Posted January 13, 2015 So is this code causing the errors or are these errors only appearing when you dont have the $count = 1; line? Only asking because you said if you set the variable before the loop, it works. Even though PHP is a bit loose with it's variables, you still should define them before you use them. It will avoid things like this. Edit: I should stop commenting before coffee... Let me make that wall of text into a TL;DR: You can't use variables in a conditional statement without first defining them :) ? Link to comment Share on other sites More sharing options...
G+_Matthew Reardon Posted January 13, 2015 Author Share Posted January 13, 2015 Right, when count is not defined ($count=1) before the loop it throws the errors. Link to comment Share on other sites More sharing options...
G+_Nate Follmer Posted January 14, 2015 Share Posted January 14, 2015 Yeah so to use a variable in a conditional statement you must "define" it first or in your case define and assign the value 1. You can hide those notices, but it's best not to, as it's telling you there is a possible bug in your code. Link to comment Share on other sites More sharing options...
G+_Jeff Brand Posted January 15, 2015 Share Posted January 15, 2015 PHP has different levels of complaints. Fatal, Warning, Notice, (and more.) Notices, most often when trying to access an undefined variable are usually hidden in shared hosting environments. Some developers like myself had developed bad habits such as undeclared variables over the course of years. (That's a stark contrast to my ASP classic days where Option Explicit was always the first line.) To be accurate, Nathan Follmer , you can use an unset variable in a conditional statement but it will evaluate as false. Type comparison in PHP is loose, as with many scripting languages. While pages like (http://php.net/manual/en/types.comparisons.php) aren't necessary for the beginner to fully understand, a general understanding of when PHP might think something is FALSE can prevent lots of frustration and bugs. These days I try to enable all messages during development and hide them in production, while still logging them to the error logs. Further best practices: * Declare variables early, even if it's to false, 0, empty string, or null. * Use isset(), empty(), or defined() (for constants) to check for unset elements while avoiding Notices * Wrap your code in a function to separate your variables from the global variable space Perhaps that last one will be covered in a future episode.. Link to comment Share on other sites More sharing options...
Recommended Posts