- empty
- Parameters
- Return Values
- Examples
- Notes
- See Also
- User Contributed Notes 36 notes
- Check if Post Exists in PHP
- Check if $_POST Exists With isset()
- Check if $_POST Exists With the Empty() Function
- Check if $_POST Exists With isset() Function and Empty String Check
- Check if $_POST Exists With Negation Operator
- Related Article — PHP Post
- if (! empty ($ _ POST)) не работает
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’ ]));
?>?php
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 ;
>
>
>
$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.
Check if Post Exists in PHP
- Check if $_POST Exists With isset()
- Check if $_POST Exists With the Empty() Function
- Check if $_POST Exists With isset() Function and Empty String Check
- Check if $_POST Exists With Negation Operator
PHP $_POST is a super-global variable that can contain key-value pair of HTML form data submitted via the post method. We will learn different methods to check if $_POST exists and contains some data in this article. These methods will use isset() , empty() , and empty string check.
Check if $_POST Exists With isset()
The isset() function is a PHP built-in function that can check if a variable is set, and not NULL. Also, it works on arrays and array-key values. PHP $_POST contains array-key values, so, isset() can work on it.
To check if $_POST exists, pass it as a value to the isset() function. At the same time, you can check if a user submitted a particular form input. If a user submits a form input, it will be available in $_POST , even if it’s empty.
The following HTML provides us with something to work with. It has a form field with a prepopulated name field.
form method="post" action=""> label>First Namelabel> input type="text" name="first_name" value="DelftStack"> input type="submit"> form>
The following PHP will check if $_POST exists when you click the submit button:
php if (isset($_POST['first_name'])) $first_name = $_POST['first_name']; echo $first_name; > ?>
Check if $_POST Exists With the Empty() Function
The following HTML is like the previous one, this time, the name is different:
form method="post" action=""> label>First Namelabel> input type="text" name="first_name" value="Mathias Jones"> input type="submit"> form>
The next code block will show you how to check for $_POST with the empty() function:
php if (!empty($_POST)) $first_name = $_POST['first_name']; echo $first_name; > ?>
Check if $_POST Exists With isset() Function and Empty String Check
The isset() function returns true if the value of $_POST is an empty string, but it will return false for NULL values. if you try to print the values of isset($_POST[‘x’]) = NULL and isset($_POST[‘x’]) = » , in both cases, you’ll get an empty string.
As a result, you will need to check for empty strings. The combination of isset() and empty string check eliminates the possibility that $_POST contains empty strings before you process its data.
In the next code block, we have an HTML to work with:
form method="post" action=""> label>First Namelabel> input type="text" name="first_name" value="Mertens Johanssen"> input type="submit"> form>
php if (isset($_POST['first_name']) && $_POST['first_name'] !== "") $first_name = $_POST['first_name']; echo $first_name; > ?
Check if $_POST Exists With Negation Operator
The negation operator (!) will turn a true statement into false and a false statement into true. Therefore, you can check if $_POST exists with the negation operator. To check for $_POST , prepend it with the negation operator in an if-else statement.
In the first part, if $_POST is empty, you can stop the p processing of its data. In the second part of the conditional, you can process the data.
form method="post" action=""> label>First Namelabel> input type="text" name="first_name" value="Marcus Alonso"> input type="submit"> form>
The next code block demonstrates checking if $_ POST exists with the negation operator.
php if (!$_POST) echo "Post does not exist"; > else $first_name = $_POST['first_name']; echo $first_name; > ?>
Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.
Related Article — PHP Post
if (! empty ($ _ POST)) не работает
У меня есть php-форма (код для последующего) с кнопкой отправки, которая запускает JSON-events.php качестве своего action ( method = POST ). В коде JSON-events я проверяю, была ли форма отправлена с использованием if (!empty($_POST)) . Моя проблема в том, что код JSON-событий, похоже, не распознает $_POST .
Здесь находится секция бокового кода формы.
json-events.php" method="post" > Search
Category 1
Category 2
Category 3
Category 4
Category 5
Category 6
Category 7
Category 8
Category 9
Category 10
любая помощь очень ценится
empty() будет работать, если $_POST не имеет никаких значений ( пустой массив ), но в вашем случае, когда вы отправляете без каких-либо значений, вы получаете массив, как показано ниже, и он не пуст:
массив ( [searchlat] => [searchlong] => [поиск] => Отправить запрос )
empty() вернет true, только если $_POST вернется
Но это не произойдет, так как каждая форма будет иметь одну кнопку Sumbit .
чтобы проверить, есть ли сделанная запись, используйте это:
if( $_SERVER['REQUEST_METHOD'] == 'POST')
Условия, которые вы можете использовать с $ _POST
if(count($_POST)>0) < //. >if(isset($_POST['field_name'])) < //. >if( $_SERVER['REQUEST_METHOD'] == 'POST') < //.. >
if(!empty($_POST['search']) && isset($_POST['search']))
гораздо лучше проверить фактическое значение в массиве $ _POST. Например.
Использование empty () не будет выполнено, если будет отправлено значение 0 Так что лучше использовать
isset($_POST['FIELD_NAME'])