Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if a string is empty

Short answer

Compare the string with an empty string using the strict operator:

<?php
 
$name = '';
 
var_dump($name === '');

Output:

bool(true)

A string of spaces

A user may type nothing but spaces. Remove them with trim() before the check:

<?php
 
$name = '   ';
 
var_dump(trim($name) === '');

Output:

bool(true)

Why not empty()

empty() treats the string '0' as empty too. If zero is a valid answer, that check gets it wrong:

<?php
 
$quantity = '0';
 
var_dump(empty($quantity));
var_dump($quantity === '');

Output:

bool(true)
bool(false)

Functions used in this recipe

  • trim — Removes whitespace and other characters from both ends of a string.
  • empty — Checks that a variable does not exist or holds an "empty" value.
  • mb_strlen — Returns the number of characters in a string.

Thanks for reading!

Donate to the site — we work hard for you.