Basit php if çift kontrol sorgu

4 Cevap php

Bu kod ile yanlış bir şey var mı?

<?php

$variable = ;

if (isset($variable))

{

echo $variable ;
echo "also this" ;

}

else

echo "The variable is not set" ;

?>

Ayrıca, değişken diğer potansiyel değerdir:

$variable = <a href="http://www.mysite.com/article">This Article</a>;

Netleştirmek için, iki olası değerden birini tutabilir bir değişken var: onunla bir a href etiketi tüm url, ya notihng bulunuyor. Ben belki ama bunu doğru şekilde yapmıyorum, bu olguların her biri için iki farklı çıktılar olması gerekir!

4 Cevap

PHP ayarlı olup olmadığını kontrol etmek için bir değişkeni başlatmak gerekmez. Kodunuzun ilk satırı değil, sadece geçersiz, ama aynı zamanda gereksiz olduğunu.

Edit: Okay yorum sizin açıklama başına, değişken her zaman ayarlanır, ancak bazen metin içeren ve bazen boş bir dize içerir. Bu durumda, ben yorumlarında @ prodigitalson tarafından tavsiye takip yapardı:

if (isset($variable) && !empty($variable))
{
    // do set stuff here
}
else
{
    // not set, do blank stuff here
}

olmalıdır:

<?php


if (isset($variable))
{

    echo $variable ;
    echo "also this" ;

}

else
{
    echo "The variable is not set" ;
}    

?>

Ya da daha özlü:

<?php echo isset($variable) ? $variable."\nalso this" : null; ?>

hat bir devletler

$variable = ;

You can't do this... you need to set the variable to something, veya unset it. E.g

$variable = '';

veya

unset($variable);

It would help in future if you posted the errveya message you were receiving, as that would help us to help you!

$variable = ;

geçersiz. olmalıdır

$variable = null; // or any other empty value

Eğer gerçekten tüm değişken tanımı dahil etmek gerekiyorsa