Define empty string php

How to check whether a String is empty in PHP

As a developer, you may get to a point where you are not sure if a string has a value or is empty. This can happen especially when the value of the string is dynamic and user-generated.

An empty string has a blank value in between the quotes (for quoted strings) or in between the opening and closing delimiter identifiers (for heredoc or nowdoc strings).

In this article, I will take you through the different methods of checking whether a string is empty or not.

Examples of empty strings:

How to check if a string is empty in PHP

1. Using the empty() function

This is the simplest and the most straightforward way. The empty() is an inbuilt PHP function that checks whether a variable is empty or not.

Syntax

The variable is a mandatory parameter that specifies which string variable to check.

The function returns FALSE if the variable exists and is not empty or TRUE if otherwise.

Example 1

Example 2

2. Using the strlen() function

The strlen() function returns the length of a string.

Syntax

The string is a mandatory parameter that specifies the string in which to check the length.

The function returns the length of a string (in bytes) on success, and 0 if the string is empty. Therefore, to determine if a string is empty or not, we just check its length and compare it with 0. If it is greater than 0 then the string is not empty. Else, we consider it empty.

Example 1

Example 2

3. Comparing it with an empty string

An empty string is equivalent to empty quotes, ie » or «» .

We just compare our string variable with empty quotes using the identical === operator. If the string is identical to the value of empty quotes, we conclude it’s empty. If else, then we know it is not empty.

Example 1

Example 2

That’s all for this article.

That is how you check if a string is empty or not in PHP.

  • Creating and working with Strings in PHP
  • How to make multi-line Strings in PHP
  • How to convert a string into a number using PHP
  • How to remove all spaces from a String in PHP
  • How to remove special characters from a String in PHP
  • How to do String to Array conversion in PHP
  • How to do Array to String conversion in PHP
  • How to check if a string contains a certain word/text in PHP
  • How to replace occurrences of a word or phrase in PHP string
  • Regex to remove an HTML tag and its content from PHP string
  • Variables, arrays and objects interpolation in PHP strings
  • How to insert a dash after every nth character in PHP string
  • How to change case in PHP strings to upper, lower, sentence, etc
  • Counting the number of characters or words in a PHP string
Читайте также:  Html код градиент фона

Источник

empty

Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals false . empty() does not generate a warning if the variable does not exist.

Parameters

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

Return Values

Returns true if var does not exist or has a value that is empty or equal to zero, aka falsey, see conversion to boolean. Otherwise returns false .

Examples

Example #1 A simple empty() / isset() comparison.

// Evaluates to true because $var is empty
if (empty( $var )) echo ‘$var is either 0, empty, or not set at all’ ;
>

// Evaluates as true because $var is set
if (isset( $var )) echo ‘$var is set even though it is empty’ ;
>
?>

Example #2 empty() on String Offsets

$expected_array_got_string = ‘somestring’ ;
var_dump (empty( $expected_array_got_string [ ‘some_key’ ]));
var_dump (empty( $expected_array_got_string [ 0 ]));
var_dump (empty( $expected_array_got_string [ ‘0’ ]));
var_dump (empty( $expected_array_got_string [ 0.5 ]));
var_dump (empty( $expected_array_got_string [ ‘0.5’ ]));
var_dump (empty( $expected_array_got_string [ ‘0 Mostel’ ]));
?>

The above example will output:

bool(true) bool(false) bool(false) bool(false) bool(true) bool(true)

Notes

Note: Because this is a language construct and not a function, it cannot be called using variable functions, or named arguments.

Note:

When using empty() on inaccessible object properties, the __isset() overloading method will be called, if declared.

See Also

  • isset() — Determine if a variable is declared and is different than null
  • __isset()
  • unset() — Unset a given variable
  • array_key_exists() — Checks if the given key or index exists in the array
  • count() — Counts all elements in an array or in a Countable object
  • strlen() — Get string length
  • The type comparison tables

User Contributed Notes 36 notes

$testCase = array(
1 => » ,
2 => «» ,
3 => null ,
4 => array(),
5 => FALSE ,
6 => NULL ,
7 => ‘0’ ,
8 => 0 ,

foreach ( $testCase as $k => $v ) if (empty( $v )) echo »
$k => $v is empty» ;
>
>
/**
Output
1=> is empty
2=> is empty
3=> is empty
4=>Array is empty
5=> is empty
6=> is empty
7=>0 is empty
8=>0 is empty
**/
?>

Please note that results of empty() when called on non-existing / non-public variables of a class are a bit confusing if using magic method __get (as previously mentioned by nahpeps at gmx dot de). Consider this example:

class Registry
protected $_items = array();
public function __set ( $key , $value )
$this -> _items [ $key ] = $value ;
>
public function __get ( $key )
if (isset( $this -> _items [ $key ])) return $this -> _items [ $key ];
> else return null ;
>
>
>

Читайте также:  Simple menu in python

$registry = new Registry ();
$registry -> empty = » ;
$registry -> notEmpty = ‘not empty’ ;

var_dump (empty( $registry -> notExisting )); // true, so far so good
var_dump (empty( $registry -> empty )); // true, so far so good
var_dump (empty( $registry -> notEmpty )); // true, .. say what?
$tmp = $registry -> notEmpty ;
var_dump (empty( $tmp )); // false as expected
?>

The result for empty($registry->notEmpty) is a bit unexpeced as the value is obviously set and non-empty. This is due to the fact that the empty() function uses __isset() magic functin in these cases. Although it’s noted in the documentation above, I think it’s worth mentioning in more detail as the behaviour is not straightforward. In order to achieve desired (expexted?) results, you need to add __isset() magic function to your class:

class Registry
protected $_items = array();
public function __set ( $key , $value )
$this -> _items [ $key ] = $value ;
>
public function __get ( $key )
if (isset( $this -> _items [ $key ])) return $this -> _items [ $key ];
> else return null ;
>
>
public function __isset ( $key )
if (isset( $this -> _items [ $key ])) return ( false === empty( $this -> _items [ $key ]));
> else return null ;
>
>
>

$registry = new Registry ();
$registry -> empty = » ;
$registry -> notEmpty = ‘not empty’ ;

var_dump (empty( $registry -> notExisting )); // true, so far so good
var_dump (empty( $registry -> empty )); // true, so far so good
var_dump (empty( $registry -> notEmpty )); // false, finally!
?>

It actually seems that empty() is returning negation of the __isset() magic function result, hence the negation of the empty() result in the __isset() function above.

Источник

PHP empty

Summary: in this tutorial, you’ll learn how to use the PHP empty() construct to check if a variable is empty.

Introduction to the PHP empty() construct

The empty() construct accepts a variable and returns true if the variable is empty. Otherwise, it returns false .

empty(mixed $v): boolCode language: PHP (php)

A variable is empty when if it does not exist or if its value is equal to false . In other words, a variable that is not set is empty or its value equals the following:

The false The integer 0 The float 0.0 and -0.0 The string "0" The empty string '' An array with no element null SimpleXML objects created from empty elements that have no attributes.Code language: PHP (php)

The empty($v) is essentially the same as the following expression that uses the isset() and equality ( == ) operator:

!isset($v) || $v == falseCode language: PHP (php)

Like the isset() construct, the empty() is a language construct, not a function. Therefore, you cannot call it using variable functions.

However, you can work around it by defining a function that uses the empty() construct and call that function using variable functions:

 function not_exist_or_false($var) : bool < return empty($var); >Code language: HTML, XML (xml)

Alternatively, you can use the arrow function syntax to define a new function that uses the empty() construct:

 $empty = fn($var) => empty($var);Code language: HTML, XML (xml)

PHP empty() examples

The following example returns true because the $count variable is not declared:

 var_dump(empty($count));Code language: PHP (php)
bool(true)Code language: PHP (php)

The following example also returns true because $count is zero, which is considered false :

 $count = 0; var_dump(empty($count));Code language: PHP (php)
bool(true)Code language: PHP (php)

If a variable’s value is false , then the empty() returns true . The following returns true for all the falsy values in the $falsy_values array:

 $falsy_values = [false, 0, 0.0, "0", '', null, []]; foreach($falsy_values as $value) < var_dump(empty($value)); >Code language: PHP (php)

When to use the PHP empty() construct

In practice, you use the empty() construct in the situation that you’re not sure if a variable even exists.

For example, suppose you receive an array $data from an external source, e.g., an API call or a database query.

To check if the $data array has an element with the key ‘username’ and it is not empty, and you may use the following expression:

isset($data['username']) && $data['username'] !== '')Code language: PHP (php)

However, it’s shorter you use the empty() construct:

!empty($data['username'])Code language: PHP (php)

Summary

Источник

How to Check Whether a Variable is Empty in PHP

$var: This variable is being checked and is the required parameter.

Below PHP 5.5, empty() only supports variables; anything else will result in a parse error. The following statement will not work empty(trim($var)). Instead, use trim($name) == false.

Return Value

It returns FALSE when $var exists and has a non-empty, non-zero value. Otherwise, it returns TRUE.

These values are considered to be an empty value:

  1. “(an empty string)
  2. 0 (0 as an integer)
  3. 0.0 (0 as a float)
  4. “0” (0 as a string)
  5. NULL
  6. FALSE
  7. array() (an empty array)

Example 1: PHP empty() function with a string

 $mage = ''; if(empty($mage))  echo 'It\'s empty'; > else  echo 'Eleven is full'; > 

If a variable is not defined or does not exist, it will be considered empty.

If you have declared a variable and are not given any value, this will still be considered empty.

How to Check if an integer variable is empty

 $num = 0; if(empty($num))  echo 'It\'s empty'; > else  echo 'It is not'; > 

How to Check if an Array is Empty

 $num = []; if(empty($num))  echo 'It\'s empty'; > else  echo 'It is not'; > 

An empty array is also taken as “empty”.

How to check if the boolean variable is empty

 $app = FALSE; if(empty($app))  echo 'It\'s empty'; > else  echo 'It is not'; > 

If a Boolean variable is False, this is also considered empty.

How to Check if an Object is Empty

Let’s define the empty class, create an object, and then check it with an empty() function.

 class App > $data = new App(); if(empty($data))  echo 'Class is empty'; > else  echo 'Class is not empty'; > 

That means that $data is not empty, and some properties are there.

A variable with a NULL value is also taken as empty.

Источник

Оцените статью