How to check if a variable is empty or not in php. Practice using the PHP empty() function. PHP empty() for objects and arrays

Modern programming has been successfully manipulating untyped variables for a long time. The type of the variable can not be specified in advance and can be changed during program execution.

This concept has become basic in the general programming paradigm. At the very beginning of the programming era, languages ​​with the same thorough confidence required the programmer to pre-define variables and strictly ensured that nothing illegal was assigned to them. Neither programs nor programming languages ​​had any idea before that a variable changes its type.

About the empty and non-existent

The PHP empty() function is the inverse of the isset() function and has some special usage features. If there is no variable, then the first function responds positively and its result is true, and the second one responds negatively, that is, its value will be false.

By definition, isset() is designed to check the existence of a variable. It doesn’t matter what and how the variable was assigned, the main thing is that it exists and is not destroyed by the unset() function. The result of the isset() function will be positive - true. It is important to remember that if $iVar = 0; then isset($iVar) will be true, but empty($iVar) will also be true.

In the first case, the result means that the variable exists, in the second case, the variable is empty, that is, the value “0” in any form, be it a string (“0”) or a number (fractional - 0.0 or integer - 0) is the same: empty($iVar) will be true.

About security and control

Practice shows that untyped languages ​​give much more freedom to the programmer, but assume that his attitude to working on the algorithm is more responsible.

PHP offers a modern syntax that supports established semantics, has few errors, but requires careful attention. For example, calling any function requires a certain number of parameters.

When calling a function, it is not at all necessary to pass all the parameters; you can pass only a significant part of them. The function "must" check the presence and existence of all parameters. Those that are missing or have incorrect values ​​must be restored to normal form and assigned the required values.

In this context, the PHP empty() function is essential. Expression:

$a = "1;2" + 20

will assign the value 21 to the variable $a, since the first part of the expression will be represented as 1, and the second will be 20.

The result will be of type number and the PHP function empty($a) will have the result - false, that is, the variable $a is not empty.

In this context, having a function:

funcTest($a ​​= 0, $b = 20)

When calling:

$res = funcTest($aVal, $bVal)

will have what is desired, that is, the result of the function. And when called:

  • $res = funcTest($aVal. $bVal)

The function body contains only one parameter with the value "$aVal . $bVal" and most likely this parameter will be interpreted as a string of characters.

PHP empty() for objects and arrays

The language syntax has a sufficient number of constructs and functions for working with objects and arrays, but from the point of view of checking for their existence and for the presence of a value, there are no special differences from variables.

PHP empty (array) - equivalent to calling empty (simple variable). However, there are very significant considerations regarding objects. As for checking an object for existence (isset), the question hardly makes sense. Concerning PHP functions empty(), then the advisability of its use remains in question.

According to the logic of object-oriented programming, an object has its own content and its own set of methods. Only the object itself can tell whether it is empty or not empty, but not a third-party function, even if it is part of the syntax of the language.

An object and its function empty()

On this simple, but legitimate basis, every object should be considered in the context of its understanding of “emptiness”. For example, the implementation of the "Staffing table" object consists of "Employee" records. But if there is not a single employee, then in the “Staffing List” there are always options for the positions of potential employees.

At what level should I use the PHP empty object function here? At the "Staffing" level, everything exists, even if there is not a single employee. At the "Employee" level, the object already exists, even if it is not completely filled. A not completely filled object can be classified as an empty object. There is no benefit from it to the staffing table.

Depending on your programming style, the PHP functions empty() and isset() are very important for building a safe and reliable algorithm, but for objects it is still better to have a variant of empty() defined by its content.

variable string (12)

I have a function isNotEmpty that returns true if the string is not empty and false if the string is empty. I found out that it doesn't work if I pass an empty line through it.

Function isNotEmpty($input) ( $strTemp = $input; $strTemp = trim($strTemp); if(strTemp != "") //Also tried this "if(strlen($strTemp) > 0)" ( return true ; ) return false ;

The string is checked using isNotEmpty:

If(isNotEmpty($userinput["phoneNumber"])) ( //validate the phone number ) else ( echo "Phone number not entered
"; }

If the line is empty, else is not executed, I don't understand why, can someone shed some light on this please.

Answers

if you have a field namely serial_number and you want to check for empty space

$serial_number = trim($_POST); $q="select * from product where user_id="$_SESSION""; $rs=mysql_query($q); while($row=mysql_fetch_assoc($rs))( if(empty($_POST["irons"]))( $irons=$row["product1"]; )

this way you can iterate through all loops in a loop with another empty function

Well, instead of answering (I believe you have already fixed your problem), I will give you some advice.

I don't know about everyone else, but I personally get very annoyed when I see something like:

If(<>) ( return true; ) return false;

this requires an elegant " return (<>); " Please always look at your code and remove this logic. For each situation you don't need the IF statement.

I'm just writing mine own function is_string for type checking and strlen for length checking.

Function emptyStr($str) ( return is_string($str) && strlen($str) === 0; ) print emptyStr("") ? "empty" : "not empty"; // empty

EDIT: You can also use the trim function to check if a string does not contain.

Is_string($str) && strlen(trim($str)) === 0;

PHP has a built-in function called empty() The test is done by typing if(empty($string))(...) php.net link: php empty

You have the answer, but in your case you can use

Return empty($input);

Return is_string($input);

Simple problem. Change:

If(strTemp != "")

If($strTemp != "")

Perhaps you can also change it to:

If($strTemp !== "")

since != "" will return true if you pass the numeric number 0 and a few other cases due to PHP's automatic type conversion.

Also keep in mind that PHP already has an empty() function.

PHP evaluates an empty string to false, so you can simply use:

If (trim($userinput["phoneNumber"])) ( // validate the phone number ) else ( echo "Phone number not entered
"; }

I always use regular expression for checking for an empty string, dating back to the days of CGI/Perl as well as Javascript, so why not PHP for example (albeit untested)

Return preg_match("/\S/", $input);

Where \S represents any character without spaces

Just use the strlen() function

If (strlen($s)) ( // not empty )

I recently asked myself the same question.
There are several possible solutions, there are 3 valid ones:

  • s.indexOf(starter) === 0
  • s.substr(0,starter.length) === starter
  • s.lastIndexOf(starter, 0) === 0 (added after viewing Mark Bayer's answer)
  • using a loop:

    Function startsWith(s,starter) ( for (var i = 0,cur_c; i< starter.length; i++) { cur_c = starter[i]; if (s[i] !== starter[i]) { return false; } } return true; }

I haven't come across the latter solution which involves using a loop.
Surprisingly, this solution is significantly superior to the first 3.
Here's the jsperf test I ran to come to this conclusion: http://jsperf.com/startswith2/2

ps: ecmascript 6 (harmony) introduces its own startsWith method for strings.
Think how much time would have been saved if they had thought to include this much needed method in the first version.

Update

Note that there are 2 loop optimizations that Steve included, the first of the two showed better performance, so I'll post that code below:

Function startsWith2(str, prefix) ( if (str.length< prefix.length) return false; for (var i = prefix.length - 1; (i >= 0) && (str[i] === prefix[i]); --i) continue;< 0; }

return i IN PHP meanings
FALSE and NULL and their associated values ​​are different from how they are usually used in other languages ​​and have their own peculiarities.
The article discusses these features.

For beginners, this can be useful for seeing the full picture; for experienced readers, it can be useful to refresh their memory if some nuance has slipped their mind.

FALSE in If statements
  • According to the PHP documentation, the following values ​​are FALSE after casting to boolean:
  • the boolean value itself is FALSE
  • an empty string ("") and the string "0".
  • empty array (array) – array().
  • an object with zero member variables (PHP 4 only, not covered in this article)
  • special NULL value (including unset variables)
SimpleXML objects (not covered in this article)
This means that if such values ​​are passed to the condition:
if (…) echo “1”; else echo “0”;

then the string "0" will be printed.

If the value of the variable is not set (unset), then a warning may also be issued. Let us remind you that the warning in the condition can be removed by writing @ before the variable.

For example:
If (@$undefVar) ( …)

But you should use @ only in extreme cases, when you have thought carefully and there are no other suitable options. See isset() function.

is_null() returns TRUE only for variables that are not assigned any value or that are assigned the value NULL .
isset() returns one-to-one boolean values ​​compared to is_null() .
If the variable is not assigned a value, then is_null() also issues an "Undefined variable" warning, unlike isset(), which does not issue any warning.
Recall that in order to remove the value of a variable, you can use the unset() function. You can also assign the value NULL for this purpose to avoid compiler warnings when trying to read the value of a variable.

Please note that, unlike variables, to work with constants you must use the defined() construct.

String representation

Let's look at the string representation of false constants.
For example, concatenation converts the values ​​into the following strings, shown in the table below:

The topic of converting to strings is described in more detail on the official website in the paragraph Converting to string.

Comparison Operators

Let's move on to comparison operators.
All false values ​​return true, as expected, when compared to FALSE using the " == " operator.
But you should not rely on transitivity here when comparing false string constants with each other.
Here is a complete table for comparing false values ​​(plus denotes table elements that, when compared using the " != " operator, return a true value:

$undef – a variable that has not been assigned a value

Some pleasant conclusions can be drawn from the table:
1. If we know that we only use strings, then we can safely compare them and not worry that "" (an empty string) will be equal to "0".
2. Arrays are never equal to strings, integers, or real numbers.

Since the types of different false constants are different, a pair of operators === and !== can be used to distinguish them.
The === operator returns false for all pairs of false values.
Returns true value only for arguments one of which is assigned the value NULL, and the second is not assigned any value.

Difference between variables with NULL value and undefined variables

The === operator allows you to distinguish between all false values, except variables with a NULL value from variables that have not been assigned a value.

Such variables can be distinguished using the get_defined_vars() function.

If you need to determine whether a value has been assigned to the $var variable, the following code snippet can be used to do this:
if (array_key_exists("var", get_defined_vars())) ( echo "var is defined"; // $var is assigned NULL ) else ( echo "var is NOT defined"; // $var is not defined or unset($ var) was called)

conclusions

You should always remember that in PHP, two false values ​​may not be equal to each other, and variables that appear to be different at first glance may turn out to be the same when compared. To avoid such surprises, you can use the === and !== operators.

When working with arrays, to avoid surprises, you can write a function to convert values ​​into guaranteed different indexes. After that, the elements of the array can only be accessed using it. This may slow down the program, but will help avoid surprises.

Testing was carried out on PHP 5.3.1.

Additional links

1. PHP type comparison tables.
2. MySQl Null and Empty Strings in context of PHP.

Tags: Add tags

In PHP, the values ​​FALSE and NULL and their associated values ​​are different from how they are usually in other languages ​​and have their own non-obvious features.
FALSE and NULL and their associated values ​​are different from how they are usually used in other languages ​​and have their own peculiarities.
The article discusses these features.

For beginners, this can be useful for seeing the full picture; for experienced readers, it can be useful to refresh their memory if some nuance has slipped their mind.

FALSE in If statements
  • According to the PHP documentation, the following values ​​are FALSE after casting to boolean:
  • the boolean value itself is FALSE
  • an empty string ("") and the string "0".
  • empty array (array) – array().
  • an object with zero member variables (PHP 4 only, not covered in this article)
  • special NULL value (including unset variables)
SimpleXML objects (not covered in this article)
This means that if such values ​​are passed to the condition:
if (…) echo “1”; else echo “0”;

then the string "0" will be printed.

If the value of the variable is not set (unset), then a warning may also be issued. Let us remind you that the warning in the condition can be removed by writing @ before the variable.

For example:
If (@$undefVar) ( …)

But you should use @ only in extreme cases, when you have thought carefully and there are no other suitable options. See isset() function.

is_null() returns TRUE only for variables that are not assigned any value or that are assigned the value NULL .
isset() returns one-to-one boolean values ​​compared to is_null() .
If the variable is not assigned a value, then is_null() also issues an "Undefined variable" warning, unlike isset(), which does not issue any warning.
Recall that in order to remove the value of a variable, you can use the unset() function. You can also assign the value NULL for this purpose to avoid compiler warnings when trying to read the value of a variable.

Please note that, unlike variables, to work with constants you must use the defined() construct.

String representation

Let's look at the string representation of false constants.
For example, concatenation converts the values ​​into the following strings, shown in the table below:

The topic of converting to strings is described in more detail on the official website in the paragraph Converting to string.

Comparison Operators

Let's move on to comparison operators.
All false values ​​return true, as expected, when compared to FALSE using the " == " operator.
But you should not rely on transitivity here when comparing false string constants with each other.
Here is a complete table for comparing false values ​​(plus denotes table elements that, when compared using the " != " operator, return a true value:

$undef – a variable that has not been assigned a value

Some pleasant conclusions can be drawn from the table:
1. If we know that we only use strings, then we can safely compare them and not worry that "" (an empty string) will be equal to "0".
2. Arrays are never equal to strings, integers, or real numbers.

Since the types of different false constants are different, a pair of operators === and !== can be used to distinguish them.
The === operator returns false for all pairs of false values.
Returns true value only for arguments one of which is assigned the value NULL, and the second is not assigned any value.

Difference between variables with NULL value and undefined variables

The === operator allows you to distinguish between all false values, except variables with a NULL value from variables that have not been assigned a value.

Such variables can be distinguished using the get_defined_vars() function.

If you need to determine whether a value has been assigned to the $var variable, the following code snippet can be used to do this:
if (array_key_exists("var", get_defined_vars())) ( echo "var is defined"; // $var is assigned NULL ) else ( echo "var is NOT defined"; // $var is not defined or unset($ var) was called)

conclusions

You should always remember that in PHP, two false values ​​may not be equal to each other, and variables that appear to be different at first glance may turn out to be the same when compared. To avoid such surprises, you can use the === and !== operators.

When working with arrays, to avoid surprises, you can write a function to convert values ​​into guaranteed different indexes. After that, the elements of the array can only be accessed using it. This may slow down the program, but will help avoid surprises.

If, when working with strings, you need to check whether a string is empty, beginner programmers usually use the function strlen(). This function is quite fast because it does not perform any calculations, but simply returns the already known value of the string length, available in zval (PHP uses a C structure to store variables). But still, because strlen()- this is a function, it is a little slow because it requires several actions when called, such as converting to lowercase and searching the hash table. In some cases, you can increase the execution speed of your code by using empty()..., but also empty() You can still optimize it a little.

Let's take an example For example checking the image path, the function checks if the path is empty, then replace it with another path, for example “images/noimage.jpg”.

And so the whole task boils down to checking whether a variable of type string is empty. Let's try 4 ways:

  • if(strlen($img_path)>0)
  • if($img_path(0))
  • if(empty($img_path))
  • and one more way for last.

And so we will write in the first way:

Function check_image_path($img_path ) ( if (strlen ($img_path ) >0 ) ( $img_path = "images/noimage.jpg" ; ) return $img_path ; )

Let's carry out testing, the average test time took 1.43795800209 sec.

Thinking about it a little more... You can access the first character of the line at once, rather than the entire line. If the first character is there, then the string is not empty. The first character in the line is numbered with "0".

Function check_image_path($img_path) ( if ($img_path ( 0 ) ) ( $img_path = "images/noimage.jpg" ; ) return $img_path ; )

average test time took 1.19431300163 sec., 17% of time played

Let's try to write using empty() now:

Function check_image_path($img_path) ( if (empty ($img_path) ) ( $img_path = "images/noimage.jpg" ; ) return $img_path ; )

average test time took 1.1341319084 sec., 5% of the time played back from the previous example

Now let's look at the penultimate and final example above us. Let's see how this can be combined. think... how else can you optimize?

Function check_image_path($img_path) ( if (empty ($img_path ( 0 ) ) ) ( $img_path = "images/noimage.jpg" ; ) return $img_path ; )

average test time took 1.07465314865 sec., and again we won 5% of the time...

How does it work and why is it faster? And here $img_path(0) returns the first character... and then the function empty() checks for an empty string... the difference from the previous example is that only one character is passed to the function, and not the entire string. Thus, from the first example to the last we won 25% time.



2024 wisemotors.ru. How it works. Iron. Mining. Cryptocurrency.