This question already has answers here:
Notice: Undefined index when trying to increment an associative array in PHP
(6 answers)
Closed 5 months ago.
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 newbies but they're actually a terrific tool to spot silly typos.
In PHP 7, we can use the "null coalescing operator" (??) :
$provenienza[$option_name] = ($provenienza[$option_name] ?? 0) + 1;
It is much simpler and with less "repetition" than using isset()
Nope, the correct one is:
foreach($SociBdP as $id=>$socio)
{
if(!isset($provenienza[$option_name]))
$provenienza[$option_name]=0;
$provenienza[$option_name]++;
}
You have to be sure that the array contains the key before you increment it.
Related
This question already has answers here:
Notice: Undefined index when trying to increment an associative array in PHP
(6 answers)
Closed 4 months ago.
I wrote these PHP scripts maybe 10 years ago, most likely on PHP 4, but maybe on 3.
I worked on them a couple years ago and got them to work on PHP 5, but now my host has upgraded to PHP 7, and I am throwing undefined offset errors by the hundreds if not thousands. I was under the impression that if I try to load a value into an undefined array, that it would create the index, but apparently not. So my solution is to simply create the empty array to avoid this. I am just trying to determine if nested loops are the only solution. We are a preschool, and for my first script, my arrays are things like:
$childs_classroom[classroom][week][day_of_week]
classroom is 0-4, weeks 0-260, and dow 0-4
When I try to increment an array like this, it creates an undefined offset error every time (I believe). Is there a simpler way other than nested loops to create this array and fill it with nulls/zeroes so I don't get errors? I apologize if this is basic stuff, I've forgotten more about PHP than I remember atm.
Nested arrays are indeed automatically created (with no notice error) if you assign them, but since you say incrementing, it sounds as though you are accessing the value prior to initialization. Incrementing a non-existent variable or key with $var++ will cause warnings, as it is equal to $var = $var + 1, and the right-hand side is evaluated before the variable exists.
This can be avoided by setting the key to zero first.
In PHP7, an easy way to do this is to use $var ??= 0. This will initialize $var to 0 if it does not contain a non-zero value yet, but will not overwrite an existing non-zero value.
For example, the following code will initialize an array key, then increment it twice, without emitting e_notice warnings.
$non_existent_array['non_existent']['key'] ??= 0;
$non_existent_array['non_existent']['key']++;
var_dump($non_existent_array);
$non_existent_array['non_existent']['key'] ??= 0;
$non_existent_array['non_existent']['key']++;
var_dump($non_existent_array);
array(1) {
["non_existent"]=>
array(1) {
["key"]=>
int(1)
}
}
array(1) {
["non_existent"]=>
array(1) {
["key"]=>
int(2)
}
}
You can bypass warnings with null coalescing operator (??) in PHP7. Example:
echo $childs_classroom[classroom][week][day_of_week] ?? "N/A"
will print the value if exists, or N/A
This question already has answers here:
PHP count JSON array
(4 answers)
Closed 4 years ago.
I have some code that works fine on servers running below PHP 7, but on PHP 7 I get a warning that I need to get rid of. I need to fix the code to get rid of the warning, I can not just hide the warnings.
My issue is with the count() function. Here is the warning I am getting and the little bit of code it is referring to. The array has the possibility of having many elements, some with values and others with blank values. It is also possible that the array will be empty. I assume that when the array is empty, that is when the warning is triggered. So I am looking for a way to tell if the array has 1 or more elements, with and without blank values. As long as there is one key then the if statement should be true.
PHP Warning: count(): Parameter must be an array or an object that implements Countable
$tb_operator_meta_json = get_post_meta($tableid, 'tb_operator_meta', true);
$tb_operator_meta = json_decode($tb_operator_meta_json, true);
$tb_operator_meta = wp_unslash($tb_operator_meta);
if (count($tb_operator_meta) > 0 && $tb_operator_meta != null) {
I don't know why this was marked as a duplicate. If you read my post it is clearly not the same as the other post.
As of PHP 7.2.0
count() will now yield a warning on invalid countable
types passed to the array_or_countable parameter.
http://php.net/manual/en/function.count.php
check the array is_array() before counting.
check if it is an array or not null.
use is_array($var);
or
use (!empty($var))
This question already has answers here:
unset variable in php
(5 answers)
Closed 4 years ago.
The documentation for NULL says that if I called unset() on a variable, the variable will become NULL:
A variable is considered to be null if:
it has been assigned the constant NULL.
it has not been set to any value yet.
it has been unset().
However, this tutorial says the following will happen when calling unset() on a variable:
PHP looks in the symbol table to find the zval corresponding to this
variable, decrements the refcount, and removes the variable from the
symbol table. Because the refcount is now zero, the garbage collector
knows that there is no way of accessing this zval, and can free the
memory it occupies.
Now I tried the following code:
<?php
$x = 12345;
unset($x);
echo gettype($x);
?>
The output I got is strange, I got an error that says that the variable is undefined (which conforms with the second quote I have posted), but I also got the type of the variable which is NULL (which conforms with the first quote I have posted):
Why am I getting this strange output?
unset() destroys the specified variables.
It does not make the Variable NULL so the warning absolutely makes sense
Notice: Undefined variable: x
Reference : http://php.net/manual/en/function.unset.php
unset() destroys the specified variables. Note that in PHP 3, unset() will always return TRUE (actually, the integer value 1). In PHP 4, however, unset() is no longer a true function: it is now a statement. As such no value is returned, and attempting to take the value of unset() results in a parse error
This question already has answers here:
Should an array be declared before using it? [closed]
(7 answers)
Closed 7 years ago.
In most languages, I have to initialize an associative array before I can use it:
data = {}
data["foo"] = "bar"
But in PHP I can just do
data["foo"] = "bar"
Are there any repercussions to doing this? Is this "the right way" to write PHP?
Is the same, but is not a good idea, the next is a copy-paste from php documentation.
If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment.
Basically it's the same, and no you won't find any problem or repercussion.
But if you like you can do this:
$a = array();
You can read more in the PHP page
This question already has answers here:
Setting default values (conditional assignment)
(6 answers)
Closed 4 years ago.
what's the PHP equivalent of Ruby's "||=" assignment idiom?
The scenario is I want to instantiate an object or array "on demand," and not necessarily when a class is initialized.
I've tried to find this in the PHP docs, but I'm having difficulty finding things I need in there (miss the Ruby).
Thank you!
I don't think PHP has a similar assignment syntax. You'll have to fake it with something like this:
if (empty($someVar)) $someVar = "DefaultVal";
Note: I'm not familiar with Ruby, so I read up on the ||= operator here. I'm not sure how that operator, as explained at that link, would help you do what you want either, but whatever.
What about:
<?php $someVar ?: 'default value'; ?>
This works well with PHP 5.3.
The answer is right but if the value does not exist it will raise an E_NOTICE. For example for $_GET['key']. If key is not in the array of $_GET it will raise an E_NOTICE.
If you are working with PHP 7 (which I totally recommend to use) there's a new feature called Null Coalesce Operator.
This way it returns the result of its first operand if it exists and is not NULL, or else its second operand:
<?php $foo = $foo ?? 'default value'; ?>
This is one of those things I miss from Ruby. You can also do:
$foo = empty($foo) ? "default" : $foo;
Ugly as hell though.