PHP-verificar se a variável está indefinida
considere este estado jquery
isTouch = document.createTouch !== undefined
Eu gostaria de saber se temos uma declaração semelhante em PHP, não sendo isset (), mas literalmente verificando por um valor indefinido, algo como:
$isTouch != ""
Existe algo semelhante ao acima em PHP?
6 answers
Pode usar -
$isTouch = isset($variable);
Guardará true
se $variable
estiver definido de outro modo false
. Se necessário, remova simplesmente o !
.
Nota: Devolve TRUE se a var existir e tiver um valor que não seja nulo, falso caso contrário.
Ou se quiser verificar se false
, 0
etc também usar empty()
-
$isTouch = empty($variable);
empty()
trabalha para -
- "" (um texto vazio)
- 0 (0 como um inteiro)
- 0.0 (0 como flutuador)
- "0" (0 como um texto)
- NULL
- FALSO
- matriz() (uma lista vazia)
- $Var; (uma variável declarada, mas sem valor)
Uma outra maneira é simplesmente:
if($test){
echo "Yes 1";
}
if(!is_null($test)){
echo "Yes 2";
}
$test = "hello";
if($test){
echo "Yes 3";
}
Vai Voltar:
"Yes 3"
A melhor maneira é usar isset (), caso contrário você pode ter um erro como "indefinido $test".
Podes fazê-lo assim:
if( isset($test) && ($test!==null) )
Você não terá nenhum erro porque a primeira condição não é aceita.
Para verificar se a variável está definida, é necessário usar a função isset.
$lorem = 'potato';
if(isset($lorem)){
echo 'isset true' . '<br />';
}else{
echo 'isset false' . '<br />';
}
if(isset($ipsum)){
echo 'isset true' . '<br />';
}else{
echo 'isset false' . '<br />';
}
Este código irá imprimir:
isset true
isset false
Leia mais em https://php.net/manual/en/function.isset.php
Pode usar -
Um oprator ternário para verificar se o valor definido pelo POST/GET ou não algo assim
$value1 = $_POST['value1'] = isset($_POST['value1']) ? $_POST['value1'] : '';
$value2 = $_POST['value2'] = isset($_POST['value2']) ? $_POST['value2'] : '';
$value3 = $_POST['value3'] = isset($_POST['value3']) ? $_POST['value3'] : '';
$value4 = $_POST['value4'] = isset($_POST['value4']) ? $_POST['value4'] : '';
if(isset($variable)){
$isTouch = $variable;
}
Ou
if(!isset($variable)){
$isTouch = "";//
}
O Operador de JavaScript 'strict not equal' (!==
) em comparação com undefined
não resulta em false
valores de null
.
var createTouch = null;
isTouch = createTouch !== undefined // true
Para obter um comportamento equivalente em PHP, pode verificar se o nome da variável existe nas chaves do resultado de get_defined_vars()
.
// just to simplify output format
const BR = '<br>' . PHP_EOL;
// set a global variable to test independence in local scope
$test = 1;
// test in local scope (what is working in global scope as well)
function test()
{
// is global variable found?
echo '$test ' . ( array_key_exists('test', get_defined_vars())
? 'exists.' : 'does not exist.' ) . BR;
// $test does not exist.
// is local variable found?
$test = null;
echo '$test ' . ( array_key_exists('test', get_defined_vars())
? 'exists.' : 'does not exist.' ) . BR;
// $test exists.
// try same non-null variable value as globally defined as well
$test = 1;
echo '$test ' . ( array_key_exists('test', get_defined_vars())
? 'exists.' : 'does not exist.' ) . BR;
// $test exists.
// repeat test after variable is unset
unset($test);
echo '$test ' . ( array_key_exists('test', get_defined_vars())
? 'exists.' : 'does not exist.') . BR;
// $test does not exist.
}
test();
Na maioria dos casos, isset($variable)
é apropriado. Isso é quivalente a array_key_exists('variable', get_defined_vars()) && null !== $variable
. Se você apenas usar null !== $variable
sem pré-verificar a existência, você vai confundir seus registros com avisos, porque isso é um tente ler o valor de uma variável indefinida.
No entanto, pode aplicar uma variável indefinida a uma referência sem qualquer aviso:
// write our own isset() function
function my_isset(&$var)
{
// here $var is defined
// and initialized to null if the given argument was not defined
return null === $var;
}
// passing an undefined variable by reference does not log any warning
$is_set = my_isset($undefined_variable); // $is_set is false