Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php variables, strings and arrays: associative array returns first letter of string

I understand that, with a sting assigned to a variable, individual characters can be expressed by using the variable as an indexed array, but why does the code below, using an associative array, not just die with missing required? Why does 'isset' not throw FALSE on an array key that definitely doesn't exist?

unset($a); 

$a = 'TESTSTRING'; 

if(!isset($a['anystring'])){ 
    die('MISSING REQUIRED'); 
}else{ 
    var_dump($a['anystring']);
} 

The above example will output:

string(1) "T"

EDIT:

As indicated by Jelle Keiser, this is probably the safer thing to do:

if(!array_key_exists('required',$_POST)){ 
    die('MISSING REQUIRED'); 
}else{ 
    echo $_POST['required']; 
} 
like image 410
dmgig Avatar asked Dec 05 '25 17:12

dmgig


2 Answers

What PHP is doing is using your string as a numeric index. In this case, 'anystring' is the equivalent of 0. You can test this by doing

<?php
echo (int)'anystring';
// 0
var_dump('anystring' == 0);
// bool(true)

PHP does a lot of type juggling, which can lead to "interesting" results.

like image 64
jprofitt Avatar answered Dec 08 '25 06:12

jprofitt


$a is a string not an associative array.

If you want to access it that way you have to do something like this.

$a['anystring'] = 'TESTSTRING';
like image 23
thomasw_lrd Avatar answered Dec 08 '25 07:12

thomasw_lrd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!