if($hOne!='') {
echo 'yes';
} else {
echo 'no';
}
SO for a while i have been using the above code to determine id X variable has been set, now this was working ok until working on a wordpress site (i wont go into too much details) but basically initially the varabile has never been touched and works as intended, if you enter a value and then delete that value it seems to think its been set.
a way i got round this is to use the below code, my question is, is there a better way to do this.
Cheers
if (preg_match('/[A-Za-z]/i', $hone)) {
echo 'yes';
} else {
echo 'no';
}
Result Used the below which works as intended, thank you all:
if(isset($hone) and
!empty($hone)) {
echo '1';
} else {
echo '2';
}
Right. My advice is to go back and read the PHP documentation. Make it a week or two project to get most sections at least glimpsed at.
You want to use isset, or empty.
if (isset($hOne)) { }
will check if the variable exists,
if (empty($hOne)) { }
checks if it is set but empty.
To help you learn PHP, I'd recommend sticking this at the top of your app:
$test_server = $_SERVER['SERVER_NAME'] == "127.0.0.1" || $_SERVER['SERVER_NAME'] == "localhost" || substr($_SERVER['SERVER_NAME'],0,3) == "192";
ini_set('display_errors',$test_server);
ini_set('display_startup_errors',$test_server);
error_reporting(E_ALL|E_STRICT);
(Or if you are not working locally, just set $test_server to 1.)
isset
and empty
functions must be used to determine if variable exists and are non-empty.
But this one:
if (preg_match('/[A-Za-z]/i', $hone)) {
echo 'yes';
} else {
echo 'no';
}
Checks if variable (string) contains almost one letter (case no matter). Actually it's also pretty dumb (it uses /../i
-- ignore case, and patter A-Za-z
)
you should not just use if ($x != '')
to check if a variable is set or not. For example, I could set the variable thus $x = ''
. You should check if it's set like so: isset($x)
and check if it's set but empty: empty($x)