Strange output after calling unset() [duplicate] - php

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

Related

PHP 7 Multidimensional Array Initialization [duplicate]

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

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

PHP: isset vs is_null - When do I need to use one over another? [duplicate]

This question already has answers here:
isset vs empty vs is_null
(14 answers)
Closed 8 years ago.
I am trying to comprehend how PHP's isset() and is_null() functions are different from one another.
I do understand their difference from the manual, but cannot come up with any example of when I absolutely need to use one function over another.
It seems I can use one or the other and it wouldn't matter, except that isset doesn't throw a Notice error if the reference didn't exist, while is_null would.
If I suppress such type of errors, then in terms of functionality these 2 functions would be exactly similar.
Have I understood it correctly?
null means nothing, no value, whereas you use isset() say whether a variable isset, for example..
$var = null;
isset($var); //returns false, checks whether the variable isset,
//but it's null so will return false
is_null($var); //Returns true, checks whether the value of variable is null
From Docs :
If a variable has been unset with unset(), it will no longer be set.
isset() will return FALSE if testing a variable that has been set to
NULL.
Going further, we alter the variable value
$var = 'hello';
isset($var); //will return true as the variable is no more null
is_null($var); //will return false as variable holds a string now
If I suppress such type of errors
No you shouldn't, always turn on the error reporting, writing bad code won't help you anyways.

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.

What is the & prefix in PHP? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Reference - What does this symbol mean in PHP?
The third line of the following code, works well in my local environment but returns an error on my production server.
What does the & prefix mean and why is it returning an error on my production server?
Below is my code;
function add_real_escape_string($value) {
if (is_array($value)) {
foreach($value as &$item) {
$item = add_real_escape_string($item);
}
} else {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$value = mysql_real_escape_string($value);
}
return $value;
}
The error returned is:
Parse error: syntax error, unexpected '&', expecting T_VARIABLE or '$' in init.php on line 345
It basically is an assign by references.
More about this from the php manual can be found here!
The & means that it passes the reference rather than a copy, meaning that all changes you make to that object will also reflect outside of the scope it is used in. See http://php.net/manual/en/language.references.pass.php for more info.
To explain the error, we'd have to know what error you're getting. Would you mind pasting it for us?
the & prefix is a reference operator. It's a princple inherited from lower-level languages such as C. It means that rather than giving a copy of the variable to a function, or a loop operator etc, you ask PHP to pass its adress in memory. That way the variables given by reference are only declared once in the memory. More, you can do every typical variables operations on it...
You could also check Pointers, the ancestors of references inherited from C.
When you prefix a variable with an &, that means you are grabbing the reference the that variable.
For example, you can pass by reference.
Makes the argument be passed as reference: http://www.php.net/manual/en/functions.arguments.php
It's for passing a variable by reference, meaning if you change it within the function it will change the variable that was passed from outside as well.

Categories