Checking if string is empty php

Check if a String is Empty in PHP

This tutorial will discuss about unique ways to check if a string is empty in php.

Table Of Contents

Method 1: Using empty()

PHP Provides a function empty(), which accepts a string value as an argument, and return true if that string is empty. But before that we need to make sure that that string variable exists and its value is set.

In the below example, we will create a string object and then we will check if it is empty or not.

Let’s see the complete example,

Frequently Asked:

Method 2: Using strlen()

The strlen() function in PHP accepts a string as an argument and returns the number of characters in that string. If strlen() function returns 0, then it means that the given string is empty.

In the below example, we will create a string object and then we will check if it is empty or not.

Let’s see the complete example,

Summary

We learned about two different ways to check if a string is empty or not in PHP.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

Читайте также:  Как узнать сколько массивов php

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

empty

Проверяет, считается ли переменная пустой. Переменная считается пустой, если она не существует или её значение равно false . empty() не генерирует предупреждение, если переменная не существует.

Список параметров

Если переменная не существует, предупреждение не генерируется. Это значит, что empty() фактически является точным эквивалентом конструкции !isset($var) || $var == false

Возвращаемые значения

Возвращает true , если параметр var не существует, если значение равно нулю, либо не задано, смотрите Преобразование в булев тип. В противном случае возвращает false .

Примеры

Пример #1 Простое сравнение empty() и isset() .

// Принимает значение true, потому что $var пусто
if (empty( $var )) echo ‘$var или 0, или пусто, или вообще не определена’ ;
>

// Принимает значение true, потому что $var определена
if (isset( $var )) echo ‘$var определена, даже если она пустая’ ;
>
?>

Пример #2 empty() и строковые индексы

$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’ ]));
?>

Результат выполнения данного примера:

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

Примечания

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций или именованных аргументов.

Замечание:

При использовании функции empty() на недоступных (необъявленных) свойствах объекта будет вызван встроенный метод объекта __isset(), если он определён.

Смотрите также

  • isset() — Определяет, была ли установлена переменная значением, отличным от null
  • __isset()
  • unset() — Удаляет переменную
  • array_key_exists() — Проверяет, присутствует ли в массиве указанный ключ или индекс
  • count() — Подсчитывает количество элементов массива или Countable объекте
  • strlen() — Возвращает длину строки
  • Таблица сравнения типов

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

$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
?>

Читайте также:  Java code for mobile

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.

Источник

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.

Читайте также:  Убрать ведущие нули python

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

Источник

empty

Проверяет, считается ли переменная пустой. Переменная считается пустой, если она не существует или её значение равно FALSE . empty() не генерирует предупреждение если переменная не существует.

Список параметров

Замечание:

До PHP 5.5 empty() проверяет только переменные, и попытка проверить что-то еще вызовет ошибку синтаксиса. Другими словами, следующий код не будет работать: empty(trim($name)). Используйте вместо него trim($name) == false.

Если переменная не существует, предупреждение не генерируется. Это значит, что empty() фактически является точным эквивалентом конструкции !isset($var) || $var == false

Возвращаемые значения

Возвращает FALSE , если var существует, и содержит непустое и ненулевое значение. В противном случае возвращает TRUE .

  • «» (пустая строка)
  • 0 (целое число)
  • 0.0 (дробное число)
  • «0» (строка)
  • NULL
  • FALSE
  • array() (пустой массив)
  • $var; (переменная объявлена, но не имеет значения)

Список изменений

empty() теперь поддерживает выражения, а не только переменные.

Проверка нечислового индекса строки возвращает TRUE .

Примеры

Пример #1 Простое сравнение empty() и isset() .

// Принимает значение true, потому что $var пусто
if (empty( $var )) echo ‘$var или 0, или пусто, или вообще не определена’ ;
>

// Принимает значение true, потому что $var определена
if (isset( $var )) echo ‘$var определена, даже если она пустая’ ;
>
?>

Пример #2 empty() и строковые индексы

В PHP 5.4 был изменен способ обработки строковых индексов в empty() .

$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’ ]));
?>

Результат выполнения данного примера в PHP 5.3:

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

Результат выполнения данного примера в PHP 5.4:

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

Примечания

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций.

Замечание:

При использовании функции empty() на недоступных (необъявленных) свойствах объекта будет вызван встроенный метод объекта __isset(), если он определен.

Смотрите также

  • isset() — Определяет, была ли установлена переменная значением отличным от NULL
  • __isset()
  • unset() — Удаляет переменную
  • array_key_exists() — Проверяет, присутствует ли в массиве указанный ключ или индекс
  • count() — Подсчитывает количество элементов массива или что-то в объекте
  • strlen() — Возвращает длину строки
  • Таблица сравнения типов

Источник

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