Ubuntu Unleashed 2019 Edition: Covering 18.04, 18.10, 19.04

(singke) #1

Note that we have temporarily taken out the leading and trailing white space
from $ourstring and are using the return value of strpos() for the
conditional statement. This reads, “If the string is found, print a message; if
not, print another message.” Or does it?


Run the script, and you see that it prints the “not found” message. The
reason for this is that strpos() returns false if the substring is not found
and otherwise returns the position where it starts. Recall that any nonzero
number equates to true in PHP, which means that 0 equates to false. With
that in mind, what is the string index of the first The in your phrase? Because
PHP’s strings are zero based, and you no longer have the spaces on either side
of the string, the The is at position 0 , which your conditional statement
evaluates to false (hence, the problem).


The solution here is to check for identicality. You know that 0 and false are
equal, but they are not identical because 0 is an integer, whereas false is a
Boolean. So, you need to rewrite the conditional statement to see whether the
return value from strpos() is identical to false, and if it is, the substring
was not found:


Click here to view code image
<?php
$ourstring = "The Quick Brown Box Jumped Over The Lazy Dog";
if (strpos($ourstring, "The") !== false) {
echo "Found 'The'!\n";
} else {
echo "'The' not found!\n";
}
?>


Arrays


Working with arrays is no easy task, but PHP makes it less difficult by
providing a selection of functions that can sort, shuffle, intersect, and filter
them. (As with other functions, there is only space here to cover a selection;
this chapter is by no means a definitive reference to PHP’s array functions.)


The easiest array function to use is array_unique(), which takes an array
as its only parameter and returns the same array with all duplicate values
removed. Also in the realm of “so easy you do not need a code example” is
the shuffle() function, which takes an array as its parameter and
randomizes the order of its elements. Note that shuffle() does not return
the randomized array; it uses your parameter as a reference and scrambles it
directly. The last too-easy-to-demonstrate function is in_array(), which

Free download pdf