Hy I have a foreach loop that adds array keys to another array. I wanted to know if it' safe to increment (with ++) and uninitialize element. At the moment my code is:
foreach($SociBdP as $id=>$socio)
{
if(!isset($provenienza[$option_name]))
$provenienza[$option_name]=0;
$provenienza[$option_name]++;
}
I wanted to know if it's safe to do
foreach($SociBdP as $id=>$socio)
{
$provenienza[$option_name]++;
}
or if there is a risk (like in c++) that the default value of the array isn't 0
While it's a documented behaviour you can trust:
It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.
... it also prevents you from taking benefit of notices since you need to lower down your error reporting settings so they don't show up in the development phase:
var_dump($foo);
Notice: Undefined variable: foo in D:\tmp\borrame.php on line 3
NULL
Notices are often seen as an annoyance by newcomers but they're actually a terrific tool to spot silly typos.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With