Using variables in PHP is nearly as easy as using them in JavaScript. In PHP, variables can store numbers, strings, or objects, just as they can in JavaScript. Unlike JavaScript, however, variables names start with $ in PHP, and you don’t need to declare them, as with the var statement in JavaScript.
For example, here is how you set the variable named $sandwiches to 1:
$sandwiches = 1;
And here is how you can display the value in this variable with the echo statement:
echo "Number of sandwiches: ", $sandwiches, "<br>";
Note | You can pass multiple items to the echo statement if you separate them with commas. Also, you’re echoing HTML to the browser here, so that can include HTML elements like <br>. |
Here’s an example, variables.php, that puts variables to work. This example starts by assigning the variable $sandwiches a value of 2:
<html> <head> <title> Using variables </title> </head> <body> <h1> Using variables </h1> <? echo "Setting number of sandwiches to 2.<br>"; $sandwiches = 2; . . . ?> </body> </html>
and it echoes the number of sandwiches to the browser:
<html> . . . <? echo "Setting number of sandwiches to 2.<br>"; $sandwiches = 2; echo "Number of sandwiches: ", $sandwiches, "<br>"; . . . ?> </body> </html>
Then the code adds two more sandwiches to the total, using the PHP + operator, which acts just like the JavaScript + operator:
<html> . . . <? echo "Setting number of sandwiches to 2.<br>"; $sandwiches = 2; echo "Number of sandwiches: ", $sandwiches, "<br>"; echo "Adding 2 more sandwiches.<BR>"; $sandwiches = $sandwiches + 2; . . . ?> </body> </html>
and then the code displays the new number of sandwiches:
<html> . . . <? echo "Setting number of sandwiches to 2.<br>"; $sandwiches = 2; echo "Number of sandwiches: ", $sandwiches, "<br>"; echo "Adding 2 more sandwiches.<BR>"; $sandwiches = $sandwiches + 2; echo "Number of sandwiches now: ", $sandwiches, "<br>"; ?> </body> </html>
You can see the results in Figure 12.4.
Figure 12.4: Using variables
In addition to assigning numbers to variables, you can also assign text strings, as shown here:
$string = "Hello from PHP.";
In JavaScript, you join strings with the + operator, but in PHP, you use the dot (.) operator instead:
$string = "Hello " . "from " . "PHP.";
For more string power, PHP comes with many string functions built in:
The trim function trims spaces from the beginning and end of a string.
The substr function extracts substrings from a string.
The strpos function finds the location of a substring in a string.
The substr_replace function replaces text in a string.
The strtoupper function converts a whole string to uppercase.
The example, string.php, puts these string functions to work. It starts by trimming the extra white space off the string " I like PHP." with the trim function:
<html> <head> <title> Using strings </title> </head> <body> <h1> Using strings </h1> <? echo trim(" I like PHP."), "<br>"; . . . ?> </body> </html>
then it uses the substr function to extract the text PHP from the string "I like PHP.":
<html> <head> <title> Using strings </title> </head> <body> <h1> Using strings </h1> <? echo trim("I like PHP."), "<br>"; echo substr("I like PHP.", 7, 3), "<br>"; . . . ?> </body> </html>
The code then uses the strpos function to locate the first occurrence of PHP in the text "I like PHP." like this:
<html> . . . <? echo trim(" I like PHP."), "<br>"; echo substr("I like PHP.", 7, 3), "<br>"; echo "'PHP' starts at position ", strpos("I like PHP.", "PHP"), "<br>"; . . . ?> </body> </html>
and then the code determines how long the string "I like PHP." is:
<html> . . . <? echo trim(" I like PHP."), "<br>"; echo substr("I like PHP.", 7, 3), "<br>"; echo "'PHP' starts at position ", strpos("I like PHP.", "PHP"), "<br>"; echo "'I like PHP.' is ", strlen("I like PHP."), " characters long.<br>"; . . . ?> </body> </html>
This example also replaces like in "I like PHP." with love using substr_replace:
<html> . . . <? echo trim(" I like PHP."), "<br>"; echo substr("I like PHP.", 7, 3), "<br>"; echo "'PHP' starts at position ", strpos("I like PHP.", "PHP"), "<br>"; echo "'I like PHP.' is ", strlen("I like PHP."), " characters long.<br>"; echo substr_replace("I like PHP.", "love", 2, 4), "<br>"; . . . ?> </body> </html>
and the example winds down by converting "I like PHP." to uppercase with strtoupper:
<html> . . . <? echo trim(" I like PHP."), "<br>"; echo substr("I like PHP.", 7, 3), "<br>"; echo "'PHP' starts at position ", strpos("I like PHP.", "PHP"), "<br>"; echo "'I like PHP.' is ", strlen("I like PHP."), " characters long.<br>"; echo substr_replace("I like PHP.", "love", 2, 4), "<br>"; echo strtoupper("I like PHP."), "<br>"; ?> </body> </html>
You can see the results in Figure 12.5.
Figure 12.5: Using string functions
Table 12.1 lists all the PHP string functions and what they do.
Function | Does This |
---|---|
addslashes | Quotes a string with slashes |
bin2hex | Converts binary data into hexadecimal representation |
chop | Alias of the trim function |
chr | Returns a specific character given its ASCII code |
chunk_split | Splits a string into smaller chunks |
convert_cyr_string | Converts from one Cyrillic character set to another |
count_chars | Returns information about characters in a string |
crc32 | Calculates the crc32 polynomial of a string |
crypt | Supports one-way string encryption (hashing) |
echo | Displays one or more strings |
explode | Splits a string on a substring |
fprintf | Writes a formatted string to a stream |
get_html_translation_table | Returns the translation table |
hebrev | Converts Hebrew text to visual text |
hebrevc | Converts logical Hebrew text to visual text |
html_entity_decode | Converts all HTML entities to their applicable characters |
htmlentities | Converts all applicable characters to HTML entities |
htmlspecialchars | Converts special characters to HTML entities |
implode | Joins array elements with a string |
join | Alias of the implode function |
levenshtein | Calculates the Levenshtein distance between two strings |
localeconv | Gets the numeric formatting information |
ltrim | Strips white space from the beginning of a string |
md5_file | Calculates the md5 hash of a given filename |
md5 | Calculates the md5 hash of a string |
metaphone | Calculates the metaphone key of a string |
money_format | Formats a number as a currency string |
nl_langinfo | Queries language and locale information |
nl2br | Inserts HTML line breaks before all new lines in a string |
number_format | Formats a number with grouped thousand separators |
ord | Returns the ASCII value of character |
parse_str | Parses the string into variables |
| Displays a string |
printf | Displays a formatted string |
quoted_printable_decode | Converts a quoted-printable string to an 8-bit string |
quotemeta | Quotes meta characters |
rtrim | Strips white space from the end of a string |
setlocale | Sets locale information |
sha1_file | Calculates the sha1 hash of a file |
sha1 | Calculates the sha1 hash of a string |
similar_text | Calculates the similarity between two strings |
soundex | Calculates the soundex key of a string |
sprintf | Returns a formatted string |
sscanf | Parses input from a string according to a format |
str_ireplace | Case-insensitive version of the str_replace function |
str_pad | Pads a string with another string |
str_repeat | Repeats a string |
str_replace | Replaces all occurrences of the search string with the replacement string |
str_rot13 | Performs the rot13 transform on a string |
str_shuffle | Shuffles a string randomly |
str_split | Converts a string to an array |
str_word_count | Returns information about words used in a string |
strcasecmp | Binary case-insensitive string comparison |
strchr | Alias of the strstr function |
strcmp | Binary-safe string comparison |
strcoll | Locale-based string comparison |
strcspn | Finds the length of the initial segment not matching a mask |
strip_tags | Strips HTML and PHP tags from a string |
stripcslashes | Un-quotes string quoted with addcslashes() |
stripos | Finds position of first occurrence of a case-insensitive string |
stripslashes | Un-quotes string quoted with addslashes() |
stristr | Case-insensitive version of the strstr function |
strlen | Gets a string’s length |
strnatcasecmp | Case-insensitive string comparisons |
strnatcmp | String comparisons using a “natural order” algorithm |
strncasecmp | Binary case-insensitive string comparison of the first n characters |
strncmp | Binary safe string comparison of the first n characters |
strpos | Finds position of first occurrence of a string |
strrchr | Finds the last occurrence of a character in a string |
strrev | Reverses a string |
strripos | Finds the position of last occurrence of a case-insensitive string |
strrpos | Finds the position of last occurrence of a char in a string |
strspn | Finds the length of initial segment matching mask |
strstr | Finds the first occurrence of a string |
strtok | Tokenizes a string |
strtolower | Converts a string to lowercase |
strtoupper | Converts a string to uppercase |
strtr | Translates certain characters |
substr_compare | Binary-safe (optionally case-insensitive) comparison of 2 strings from an offset |
substr_count | Counts the number of substring occurrences |
substr_replace | Replaces text within part of a string |
substr | Returns part of a string |
trim | Strips white space from the beginning and end of a string |
ucfirst | Makes a string’s first character uppercase |
ucwords | Uppercases the first character of each word in a string |
vprintf | Outputs a formatted string |
vsprintf | Returns a formatted string |
wordwrap | Wraps a string to a given number of characters |