|
|
 |
empty (PHP 3, PHP 4, PHP 5) empty -- Determinar si una variable está
vacÃa Descripciónbool empty ( mixed var )
Determinar si una variable es considerada vacÃa.
Lista de parámetros
- var
Variable a verificar
Nota:
empty() sólo chequea variables ya
que cualquier otra cosa producirá un error de
intérprete. En otras palabras, lo siguiente no
funcionará: empty(trim($name)).
empty() es el opuesto de (boolean)
var, con la excepción
de que no se genera una advertencia cuando la variable no
está definida.
Valores retornados
Devuelve FALSE si var tiene un valor no
vacÃo y diferente de cero.
Las siguientes expresiones son consideradas como vacÃas:
| "" (una cadena vacÃa) | | 0 (0 como un entero) | | "0" (0 como una cadena) | | NULL | | FALSE | | array() (una matriz vacÃa) | | var $var; (una variable declarada, pero sin un
valor en una clase) |
Ejemplos
Ejemplo 1.
Una simple comparación empty() /
isset().
|
<?php
$var = 0;
if (empty($var)) {
echo '$var es 0, una variable vacia, o no esta definida en absoluto';
}
if (isset($var)) {
echo '$var esta definida aunque este vacia';
}
?>
|
|
NotesNota: Puesto que esto es
una construcción del lenguaje y no una función, no puede
ser llamado usando funciones
variables
r-u-d-i-e at jouwmoeder dot dot nl
10-Jul-2006 07:45
The two following methods will do exactly the same, in any case:
<?php
if ( empty($var) )
{
}
if ( !isset($var) || !$var )
{
}
?>
empty( ) checks for isset AND also the value of the variable (0, "0", "", etc).
Karl Jung
03-Jun-2006 09:03
This function I did, works like empty(), but doesn't consider zero (0) as empty.
Also, considers as empty, a string containing only blank spaces, or "\n", "\t", etc.
function my_empty($val)
{
$result = false;
if (empty($val))
$result = true;
if (!$result && (trim($val) == ""))
$result = true;
if ($result && is_numeric($val) && $val == 0)
$result = false;
return $result;
}
Values considered as EMPTY:
$val = "";
$val = " ";
$val = " \t \n ";
$val = array();
$val = false;
$val = null;
Values considered NOT EMPTY:
$val = "0";
$val = intval(0);
$val = floatval(0);
boards at gmail dot com
28-Apr-2006 11:53
Followup to ben at wbtproductions dot com:
You'll want to do this check for numeric 0:
<?
if ($data === 0) echo 'The data is zero.';
?>
Checking $data == 0 basically means the same thing as "is $data false?". Loose type checking is a gotcha you should look out for.
ben at wbtproductions dot com
18-Apr-2006 05:40
It is important to note that empty() does not check data type. This can change the functioning of any program if, at some point, your data might be all zeroes, containing no real data, but also not empty by PHP's definition.
Think about this:
$data = "00000";
if (empty($data))
echo "The data appears empty.";
if (0==$data) //Use this test for number applications!!
echo "The data is zero.";
$data = 0;
if (empty($data))
echo "Remember, zero is empty.";
outputs:
The data is zero.
Remember, zero is empty.
This could crop up in ZIP codes and phone numbers or zero-filled/zero-padded values from SQL. Watch those variable types!
nobody at example dot com
28-Feb-2006 12:06
Re: inerte is my gmail.com username's comment:
While that may be true, those two statements (empty($var), $var == '') are NOT the same. When programming for web interfaces, where a user may be submitting '0' as a valid field value, you should not be using empty().
<?php
$str = '0';
echo empty($str) ? 'empty' : 'not empty';
echo $str == '' ? 'empty' : 'not empty';
?>
Trigunflame at charter dot net
31-Jan-2006 09:35
But not faster than
if (!$var)
{
}
which is about 20% faster than empty() on php5.1
inerte is my gmail.com username
11-Nov-2005 06:58
empty() is about 10% faster than a comparision.
if (empty($var)) {
}
is faster than:
if ($var == '') {
}
YMMV, empty() also checks array and attributes, plus 0, and '' is kind a string with nothing inside. But I was using '' and got a huge performance boost with empty().
PHP 4.3.10-15, Apache/2.0.54, Kernel 2.4.27-2-386.
nahpeps at gmx dot de
19-Aug-2005 03:14
When using empty() on an object variable that is provided by the __get function, empty() will always return true.
For example:
class foo {
public function __get($var) {
if ($var == "bar") {
return "bar";
}
}
}
$object_foo = new foo();
echo '$object_foo->bar is ' . $object_foo->bar;
if (empty($object_foo->bar)) {
echo '$object_foo->bar seems to be empty';
}
produces the following output:
$object_foo->bar is bar
$object_foo->bar seems to be empty
jmarbas at hotmail dot com
01-Jul-2005 09:10
empty($var) will return TRUE if $var is empty (according to the definition of 'empty' above) AND if $var is not set.
I know that the statement in the "Return Values" section of the manual already says this in reverse:
"Returns FALSE if var has a non-empty and non-zero value."
but I was like "Why is this thing returning TRUE for unset variables???"... oh i see now... Its supposed to return TRUE for unset variables!!!
<?php
ini_set('error_reporting',E_ALL);
ini_set('display_errors','1');
empty($var);
?>
nsetzer at allspammustdie dot physics dot umd dot edu
30-Jun-2005 08:02
I needed to know if the variable was empty, but allow for it to be zero, so I created this function. I post it here in case anybody else needs to do that (it's not hard to make, but why reinvent the wheel...)
<?php
function is_extant($var)
{
if (isset($var))
{
if ( empty($var) && ($var !== 0) && ($var !== '0') )
return FALSE;
else
return TRUE;
}
else
return FALSE;
}
?>
tan_niao
09-Jun-2005 08:43
admin at prelogic dot net has wrote the following
In response to admin at ninthcircuit dot info
The best way around that is the trim function. For example:
$spaces = " ";
if(empty(trim($spaces)){
echo "Omg empty string.";
}else{
echo "Omg the string isnt empty!";
}
Hope that helps anyone, though it is rather trivial.
i think is said above that empty(trim($spaces)) dont work
,i think is better to seperate this two function
trim($spaces);
empty($spaces) thern continue with the code......
Kouenny
08-Jun-2005 06:45
In response to "admin at ninthcircuit dot info" :
Instead of using "$spaces = str_replace(" ",""," ");"
you should use the function "trim()", which clear spaces before and after the string. e.g. "trim(' example 1 ')" returns "example 1".
shorty114
27-May-2005 04:17
In Response to Zigbigidorlu:
Using if (!$_POST['foo']) is not the best way to test if a variable is empty/set. Doing that creates a E_WARNING error for an uninitialized variable, and if you are planning to use a rather high error level, this is not the better way, since this will create an error whereas if (!isset($_POST['foo'])) or (empty($_POST['foo'])) doesn't echo an error, just returns true/false appropriately.
One example of this is in the phpBB code - the coding guidelines state that you have to use isset() or empty() to see if a variable is set, since they planned to use a higher level of error reporting.
Zigbigidorlu
24-May-2005 10:44
This function is of very little use, as the "!" operator creates the same effect.
<?
if(empty($_POST['username']) exit;
?>
has the exact same functionality as:
<?
if(!$_POST['username']) exit;
?>
admin at ninthcircuit dot info
24-May-2005 10:14
Something to note when using empty():
empty() does not see a string variable with nothing but spaces in it as "empty" per se.
Why is this relevant in a PHP application? The answer is.. if you intend to use empty() as a means of input validation, then a little extra work is necessary to make sure that empty() evaluates input with a more favorable outcome.
Example:
<?php
$spaces = " ";
if (empty($spaces))
print "This will never be true!";
else
print "Told you!";
?>
To make empty() behave the way you would expect it to, use str_replace().
<?php
$spaces = str_replace(" ",""," ");
if (empty($spaces))
print "This will always be true!";
else
print "Told you!";
?>
This might seem trivial given the examples shown above; however, if one were to be storing this information in a mySQL database (or your preferred DB of choice), it might prove to be problematic for retrieval of it later on.
admin at ninthcircuit dot info
24-May-2005 10:13
Something to note when using empty():
empty() does not see a string variable with nothing but spaces in it as "empty" per se.
Why is this relevant in a PHP application? The answer is.. if you intend to use empty() as a means of input validation, then a little extra work is necessary to make sure that empty() evaluates input with a more favorable outcome.
Example:
<?php
$spaces = " ";
if (empty($spaces))
print "This will never be true!";
else
print "Told you!";
?>
To make empty() behave the way you would expect it to, use str_replace().
<?php
$spaces = str_replace(" ",""," ");
if (empty($spaces))
print "This will always be true!";
else
print "Told you!";
?>
This might seem trivial given the examples shown above; however, if one were to be storing this information in a mySQL database (or your preferred DB of choice), it might prove to be problematic for retrieval of it later on.
myfirstname dot barros at gmail dot com
29-Apr-2005 08:15
<?php
$a = Array( ); $a = Array( '' ); $a = Array( Null ); ?>
---
gabriel
rehfeld.us
23-Aug-2004 01:47
ive found the empty() contruct extremely usefull. For some reason people seem to think its of little use, but thats not so.
for example, form fields can be checked in 1 step by using empty(). (assuming a basic check of whether it was submitted and if submitted, that it was not empty.)
<?php
if (!empty($_POST['name'])) $name = $_POST['name'];
?>
compared to isSet(), this saves an extra step. using !empty() will check if the variable is not empty, and if the variable doesnt exit, no warning is generated.
with isSet(), to acheive the same result as the snippit above, you would need to do this:
<?php
if (isSet($_POST['name']) && $_POST['name']) $name = $_POST['name'];
?>
so using !empty() reduces code clutter and improves readability, which IMO, makes this VERY usefull.
paul at worldwithoutwalls dot co dot uk
22-May-2004 10:09
Note the exceptions when it comes to decimal numbers:
<?php
$a = 0.00;
$b = '0.00';
echo (empty($a)? "empty": "not empty"); echo (empty($b)? "empty": "not empty"); $c = intval($b);
echo (empty($c)? "empty": "not empty"); ?>
For those of you using MySQL, if you have a table with a column of decimal type, when you do a SELECT, your data will be returned as a string, so you'll need to do apply intval() before testing for empty.
e.g.
TABLE t has columns id MEDIUMINT and d DECIMAL(4,2)
and contains 1 row where id=1, d=0.00
<?php
$q = "SELECT * FROM t";
$res = mysql_query($q);
$row = mysql_fetch_assoc($res);
echo (empty($row['d'])? "empty": "not empty"); ?>
| |
| | Citas célebres | No es la carne y la sangre, sino el corazón lo que nos hace padres e hijos. Friedrich Schiller Escritor alemán (1759-1805) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... Mamá, mamá | | Lengua fuera | - Mamá, mamá ¿a quién le está sacando la lengua mi papá?
- A los que lo ahorcaron, hijito. A los que lo ahorcaron. | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|