IT Questions and Answers :)

Wednesday, November 29, 2017

In PHP scripting, which expression will output $somestring to the browser, only if it contains a colon?

In PHP scripting, which expression will output $somestring to the browser, only if it contains a colon?


  • if (strpos($somestring,":")!==false) echo $somestring ;
  • if (strpos($somestring,":")==true) echo $somestring ;
  • if (strpos($somestring,":")!=false) echo $somestring ;
  • if (strpos($somestring,":")=true) echo $somestring ;             
In PHP scripting, which expression will output $somestring to the browser, only if it contains a colon?


EXPLANATION

The correct test is "!==false"
The strpos() function finds the position of the first occurrence of a string inside another string. In this example, it looks for the numeric position of the first occurrence of a colon if one is present, or a boolean false value if none is found.
PHP strings are zero-indexed, so a string starting with colon (:) will return a numeric zero from strpos(). However, as in most scripting languages, the variables are not strongly typed, zero and false being equivalent in logic tests.
Thus, a string starting with a colon would cause the zero output of strpos() to be interpreted as 'Not found' and nothing would be output to the browser.
The workaround is to use a literal boolean test, which is expressed with '===' or '!==' for equality or inequality as appropriate.
The '===' test cannot be used here, because a colon's presence is returned as an integer value, which is not literally a boolean value. Thus doing so would result in no output, ever. (False or an integer are never literally equal to true.)
The correct approach is therefore to ask, 'Is the value returned by strpos() NOT LITERALLY a BOOLEAN FALSE' -which yields true for colon present anywhere including first character, false for no colon. (Also false for a null string)
Incidentally, BASIC-like languages index strings from one, so the issue does not arise. Javascript indexes strings from zero, but search functions typically return -1 as the 'not found' response.
The lowdown:
if (strpos($somestring,":")!==false) echo $somestring ; // Yay! It worked. :)
if (strpos($somestring,":")=true) echo $somestring ;     // This is a syntax error.
if (strpos($somestring,":")===true) echo $somestring ; // Never outputs anything.
if (strpos($somestring,":")!=false) echo $somestring ;   // Fails if the colon is first char, otherwise works.
if (strpos($somestring,":")==true) echo $somestring ;   // Fails if the colon is first char, otherwise works.
Share:

0 comments:

Post a Comment

Popular Posts