2

How do I go about catching an undefined variable error in PHP? I have a variable called $place that will only have a value if the user enters some details on another page, however if it has no value then it has an undefined variable error on the screen which I don't want. I tried:

<?php try{ echo $place; }catch(Exception $e){echo 'No Place Set';}?>

but that doesn't work. Any suggestions?

rockb0ttom
  • 45
  • 1
  • 1
  • 6
  • 1
    The question is fine, no editing needed because is clearly not a duplicate. This header talks about the usage of try-catch or "catching" using exception handling. However the referred one has not even a single mention to this structure. The question is fine, no editing needed – Mbotet Jan 14 '21 at 13:02

3 Answers3

2

undefined variables can be corrected by DEFINING them.

for instance:

$place = ''; OR $place = null;

defines the variable. you will not get any error or warning.

Or use if(isset($place)){}

urfusion
  • 5,528
  • 5
  • 50
  • 87
Daniel PurPur
  • 519
  • 3
  • 13
0

just use isset() to determine if the variable is set.

if(isset($place)){
    echo $place;
}else{
    echo 'No Place Set';
}
Natalie Hedström
  • 2,607
  • 3
  • 25
  • 36
urfusion
  • 5,528
  • 5
  • 50
  • 87
0

Why are you using try-catch for that? Just use isset

<?php 

if(isset($place)){
    echo $place;
} else {
    echo 'No Place Set';
}
Harikrishnan
  • 9,688
  • 11
  • 84
  • 127