1

http://codepad.org/GAl6W6xn

Why does this code say "not set"? What is array location 2 set as to make it say "set"? How can I approach this so I know if there is or isn't a value in location 2?

(sorry for lack of a good title, couldn't think of one)

dukevin
  • 22,384
  • 36
  • 82
  • 111

3 Answers3

6

well it is set, perhaps you meant to check if it was empty()

you should probably have a look at : The type comparison tables

3

you can try

if(!empty($r[2]))

ohmusama
  • 4,159
  • 5
  • 24
  • 44
2

Answer is

array_key_exists
empty

Try this

array_key_exists(2, $r);
// or
!empty($r[2]);

For more accurate

$line = "a";
$r = explode("|",$line);

print_r($r);
if(!empty($r[2])) // or use if(array_key_exists(2, $r))
    echo "array location [2] set";
else echo "array location [2] NOT set";
Wazy
  • 8,822
  • 10
  • 53
  • 98
  • What is the difference between array_key_exists and empty? – dukevin Feb 18 '12 at 06:10
  • Check this out http://stackoverflow.com/questions/6884609/array-key-existskey-array-vs-emptyarraykey . It will explain you better.. – Wazy Feb 18 '12 at 06:11
  • `array_key_exists` does not solve the original problem. Change `$line = "a";` in your example to `$line = "a||c";` and `array location [2] set` will be output, which is the same problem `isset` was causing. – lightster Feb 18 '12 at 06:34
  • @lightster Thanks for explaining the same as what was explained in http://stackoverflow.com/questions/6884609/array-key-existskey-array-vs-emptyarraykey mentioned in the 2nd comment...I totally accept on what yo said but in this case you can use `array_key_exists` too. – Wazy Feb 18 '12 at 06:37
  • @Wazzzy I'm sorry, my example was wrong. Try this: change `$line = "a";` to `$line = "a|||c";`. You will see that `!empty($r[2])` and `array_key_exists(2, $r)` do not return the same results in that case. – lightster Feb 18 '12 at 06:56