Wizard
Wizard

Reputation: 11265

How to check do variable is initialized

My example

<?php
if(something){
$message = "set";
}

echo $message; // but I can get error that variable is not unidentified ?>

My question how to check do variable is initialized to not get error "unidentified variable"

Upvotes: 1

Views: 386

Answers (4)

NullPoiиteя
NullPoiиteя

Reputation: 57322

try something like

$message = NULL;
if(something){
$message = "set";
}

if($message){
   echo $message;
}

Codepad

or check that variable is set by isset

echo isset($var)?$var:'';

Upvotes: 1

Pankaj Khairnar
Pankaj Khairnar

Reputation: 3108

<?php
if(something){
    $message = "set";
}
echo isset($message)?$message:'';//this will not give error now

?>

Upvotes: 0

Rob Apodaca
Rob Apodaca

Reputation: 834

The closest would be the isset function:

if (isset($somethink)) {
    $messege = "set";
} else {
    $message = "";
}

or

$message = (isset($somthink)) ? "set" : "";

But, note that isset checks whether the variable is defined and is not null.

Upvotes: 0

Stephen Oberauer
Stephen Oberauer

Reputation: 5365

Use isset (see http://php.net/manual/en/function.isset.php)

$message = "not set";

if (isset($var)) {
    $message = "set";
}

Upvotes: 1

Related Questions