Array element will not display

I have an array which on doing a print_r shows

Array
(
    [0] => BET
    [1] => 1807
    [2] => AND
    [3] => 1808
)

If, however, I do a check on element [2] I get nothing returned from that array element.

[php]
if ($s[2]!==“TO”||$s[2]!==“AND”) {
[/php]

Even echo returns no value for element 2 whereas print does return a value.

Any ideas what is going on here?

Need more information.

https://www.ideone.com/eOKSKb

Thanks for your help

It seems as though it was something weird with the !== as I have flipped the if else code around and just changed it to == and it works.

Well, you are doing logical OR so,

[php]if ($s[2]!==“TO”||$s[2]!==“AND”) {[/php]
“AND” doesn’t = “TO”, so it would short circuit and be true.

$a || $b Or TRUE if either $a or $b is TRUE.
From [url=http://php.net/manual/en/language.operators.logical.php]http://php.net/manual/en/language.operators.logical.php[/url]

The conditional logic you first posted will always be true (play computer and try some values.) Either the first term will be true or the second term will be true, so the end result, due to or’ing the terms, will always be true.

Using negative logic should be avoided whenever possible. Negating the posted logic results in if ($s[2] ==“TO” && $s[2] ==“AND”) {, which makes it easier to see that the condition will never be met. A single array element/variable can never be both of those values at the same time.

If what you are doing is to detect if the array element is either ‘TO’ or ‘AND’, the logic would be if ($s[2] ==“TO” || $s[2] ==“AND”) {. The negative logic of this would be if ($s[2] !==“TO” && $s[2] !==“AND”) {.

A simpler way of testing if something is (is not) one of several values, is to make an array of the expected values and use in_array() -

[php]
// value is one of the expected values
if(in_array($s[2],[‘TO’,‘AND’])) {[/php]

[php]
// value is NOT one of the expected values
if(!in_array($s[2],[‘TO’,‘AND’])) {[/php]

Thanks very much to both of you for expanding on my knowledge. I always have an issue with logical operators and regex. I put it down to my age. :wink:

What was odd echoing $s[2] before the if statement showed AND but echoing it afterwards showed nothing. That is what had me confused.

Using negative logic should be avoided whenever possible

Nice to see someone putting that out there.

Sponsor our Newsletter | Privacy Policy | Terms of Service