PHP 7 Multidimensional Array Initialization [duplicate] - php

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

Related

Message: Trying to access array offset on value of type null [duplicate]

This question already has answers here:
Trying to access array offset on value of type null
(3 answers)
Closed 3 years ago.
I'm getting this error on multiple occasion in a script (invoiceplane) I have been using for a few years now but which hasn't been maintained unfortunately by its creators:
Message: Trying to access array offset on value of type null
My server has been upgrade to PHP 7.4 and I'm looking for a way to fix the issues and maintain the script myself since I'm very happy with it.
This is what's on the line that gives the error:
$len = $cOTLdata['char_data'] === null ? 0 : count($cOTLdata['char_data']);
$cOTLdata is passed to the function:
public function trimOTLdata(&$cOTLdata, $Left = true, $Right = true)
{
$len = $cOTLdata['char_data'] === null ? 0 : count($cOTLdata['char_data']);
$nLeft = 0;
$nRight = 0;
//etc
It's included in mpdf btw, but simply overwriting the files from the github repository did not fix the errors.
This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

PHP count replacement [duplicate]

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))

Strange output after calling unset() [duplicate]

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

How to completely wipe an array? [duplicate]

This question already has answers here:
What's better at freeing memory with PHP: unset() or $var = null
(13 answers)
Closed 7 years ago.
I have some sensitive data like user data and stuff stored in arrays at times.and the problem is that with a very high probability unset behaves just like deleting on most file systems work, just remove it from the index and well, "out of sight out of mind", but I clearly want to annihilate the arrays contents, so they cannot be read anymore even if there might be a second heartbleed or similar stuff... so I want to completely overwrite the array's data so it cannot be retrieved from the ram anymore after I finished my work with it.
any ideas?
To wipe an array completely, you can either unset or overwrite it.
$array = array(1, 2, 3);
// To unset it - a var_dump will return NULL afterwards
unset($array);
// To overwrite - a var_dump will return array(0) { empty } afterwards
$array = array();

Increasing not initialize array value in php [duplicate]

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.

Categories