Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to compare empty string

Tags:

php

my code :

$disabled = $this->access->get_access('disable_header');
$emptyString = '';
var_dump($emptyString);
var_dump($disabled[0]);
if($disabled[0] == '') die('should be here');
if($disabled[0] == ' ') die('should be here');
die('stop');

and the result is :

string(0) "" string(1) "" stop

all my condition is failed and i don't know why ..
but if i make $emptyString condition :

if($emptyString == '') die('should be here');

it give me result :

should be here

if you see the both $dislabled[0] and $emptyString has the same empty string, but has different length, if i make $emptyString length to 1 then:

$disabled = $this->access->get_access('disable_header');
$emptyString = ' ';
var_dump($emptyString);
var_dump($disabled[0]);
if($disabled[0] == '') die('should be here');
if($disabled[0] == ' ') die('should be here');
die('stop');

become :

string(1) " " string(1) "" stop

i stil failed to compare $disable[0]

what i missed?

====HOW TO RESOLVE===

first i try

mb_detect_encoding($disabled[0]);

then give me result

ASCII

then i try :

var_dump(hexdec($disabled[0]))

then give me result :

int(9)

i go to ascii table and 9 = TAB key

then now i make condition :

if(strcmp($disabled[0],'')) die('should be here');

tadaaa .. it show :

should be here

i think strcmp can work for all enter, tab and space key value .. any mistake for my opinion?

like image 986
kreamik Avatar asked Jan 19 '13 11:01

kreamik


1 Answers

I think

if(empty($disabled[0])) die('should be here');

is the better way to check if a variable is empty using PHP.

"" or " " is for JavaScript.

like image 78
Semi-Friends Avatar answered Sep 25 '22 01:09

Semi-Friends