PHP Functions 6 programs with output 15 Q/A 5 MCQs

Learning Objectives – after this chapter you will be able to:

  • Look up and use PHP's string functions for length, case, searching, replacing, splitting, formatting, comparing, encoding and hashing.
  • Test and convert variable types with the variable-handling functions.
  • Use miscellaneous functions such as define(), constant(), uniqid(), sleep(), highlight_string() and pack().
  • Replace string and variable functions that were removed in PHP 7 and PHP 8.
String Functions – Length, Case and Trimming
FunctionPurpose
strlen(string)Returns the length of a string in bytes (mb_strlen() counts characters).
str_word_count(string [, format])Counts the words (or returns them as an array).
count_chars(string [, mode])Counts how often each byte value occurs.
strtolower(string) / strtoupper(string)Converts to lowercase / uppercase.
ucfirst(string) / lcfirst(string)Makes the first character uppercase / lowercase.
ucwords(string)Makes the first character of each word uppercase.
trim(string [, chars])Removes white space (or given characters) from both ends.
ltrim(string) / rtrim(string)Removes white space from the beginning / end. chop() is an alias of rtrim().
str_pad(string, length [, pad, type])Pads a string to a length (STR_PAD_RIGHT, STR_PAD_LEFT, STR_PAD_BOTH).
str_repeat(string, times)Repeats a string.
strrev(string)Reverses a string.
str_shuffle(string)Randomly shuffles the characters.
wordwrap(string [, width, break, cut])Wraps a string to a given width.
nl2br(string)Inserts <br /> before every newline.
chunk_split(string [, length, end])Splits a string into smaller chunks.
String Functions – Searching and Replacing
FunctionPurpose
strpos(haystack, needle [, offset])Position of the first occurrence (case-sensitive), or false.
stripos(...)Like strpos(), case-insensitive.
strrpos(...) / strripos(...)Position of the last occurrence (case-sensitive / insensitive).
strstr(haystack, needle)Returns the part of haystack from the first occurrence of needle. strchr() is an alias.
stristr(haystack, needle)Case-insensitive strstr().
strrchr(haystack, char)Returns the part from the last occurrence of a character.
str_contains / str_starts_with / str_ends_with (haystack, needle)Checks whether a string contains / starts with / ends with another (PHP 8).
substr(string, start [, length])Returns part of a string.
substr_count(haystack, needle)Counts occurrences of a substring.
substr_replace(string, replacement, start [, length])Replaces part of a string.
substr_compare(a, b, offset [, length, case_insensitive])Compares two strings from an offset.
str_replace(search, replace, subject [, &count])Replaces all occurrences (case-sensitive).
str_ireplace(...)Case-insensitive str_replace().
strtr(string, from, to) or strtr(string, array)Translates characters or replaces substrings.
strpbrk(string, char_list)Searches a string for any of a set of characters.
strspn(string, mask) / strcspn(string, mask)Length of the initial part that consists of / does not contain the mask characters.
strtok(string, token)Splits a string into tokens, one call at a time.
File: htdocs/phpbook/ch29/search.php
<?php
$s = "PHP is fun. Learning PHP with XAMPP is easy.";
echo "strlen: " . strlen($s) . ", str_word_count: " . str_word_count($s) . "<br>";
echo "strpos('PHP'): " . strpos($s, "PHP") . ", strrpos('PHP'): " . strrpos($s, "PHP") . "<br>";
echo "stripos('php'): " . stripos($s, "php") . "<br>";
echo "substr_count('PHP'): " . substr_count($s, "PHP") . "<br>";
echo "strstr('Learning'): " . strstr($s, "Learning") . "<br>";
echo "strrchr(' '): '" . strrchr($s, " ") . "'<br>";
echo "substr(-5): " . substr($s, -5) . "<br>";
echo "str_replace: " . str_replace("PHP", "Python", $s, $count) . " ($count replacements)<br>";
echo "str_ireplace('xampp','WAMP'): " . str_ireplace("xampp", "WAMP", $s) . "<br>";
echo "substr_replace: " . substr_replace("Hello World", "PHP", 6, 5) . "<br>";
echo "strtr: " . strtr("Hi all, I said hello", ["Hi" => "Hello", "hello" => "hi"]) . "<br>";
echo "str_starts_with('PHP'): " . var_export(str_starts_with($s, "PHP"), true) . "<br>";
echo "strtok: ";
$tok = strtok("red,green;blue", ",;");
while ($tok !== false) { echo "[$tok] "; $tok = strtok(",;"); }
?>
OUTPUT browser · http://localhost/phpbook/ch29/search.php
strlen: 44, str_word_count: 9
strpos('PHP'): 0, strrpos('PHP'): 21
stripos('php'): 0
substr_count('PHP'): 2
strstr('Learning'): Learning PHP with XAMPP is easy.
strrchr(' '): ' easy.'
substr(-5): easy.
str_replace: Python is fun. Learning Python with XAMPP is easy. (2 replacements)
str_ireplace('xampp','WAMP'): PHP is fun. Learning PHP with WAMP is easy.
substr_replace: Hello PHP
strtr: Hello all, I said hi
str_starts_with('PHP'): true
strtok: [red] [green] [blue]
String Functions – Splitting, Joining and Formatting
FunctionPurpose
explode(separator, string [, limit])Splits a string by a separator into an array. Opposite of implode().
implode(glue, array)Joins array elements into a string. join() is an alias.
str_split(string [, length])Splits a string into an array of chunks.
str_getcsv(string [, separator])Parses a CSV line into an array.
printf(format, args...)Outputs a formatted string.
sprintf(format, args...)Returns a formatted string.
vprintf / vsprintf / vfprintf (format, args_array)Like printf/sprintf/fprintf but with an array of arguments.
fprintf(stream, format, args...)Writes a formatted string to a stream (file).
sscanf(string, format, &vars...)Parses input from a string according to a format.
number_format(number [, decimals, dec_point, thousands])Formats a number with grouped thousands.
parse_str(string, &result)Parses a query string into an array.
File: htdocs/phpbook/ch29/format.php
<?php
$csv = "Asha,Bhopal,82";
$parts = explode(",", $csv);
echo "explode: " . $parts[0] . " | " . $parts[1] . " | " . $parts[2] . "<br>";
echo "implode: " . implode(" - ", ["PHP", "MySQLi", "AJAX"]) . "<br>";
echo "str_split: " . implode(" ", str_split("ABCDEFGH", 3)) . "<br>";
printf("printf: %s scored %d marks (%.1f%%)<br>", "Ravi", 456, 456 / 5);
$s = sprintf("%05d | %-8s| %8.2f | %x | %b", 42, "left", 3.14159, 255, 5);
echo "sprintf: " . str_replace(" ", "&nbsp;", $s) . "<br>";
echo "vsprintf: " . vsprintf("%s is %d years old", ["Neha", 23]) . "<br>";
sscanf("Roll: 105 Name: Kiran", "Roll: %d Name: %s", $roll, $name);
echo "sscanf: roll=$roll, name=$name<br>";
parse_str("city=Bhopal&pin=462011", $q);
echo "parse_str: " . json_encode($q) . "<br>";
echo "wordwrap: " . wordwrap("The quick brown fox jumps over the lazy dog", 15, "<br>", true);
?>
OUTPUT browser · http://localhost/phpbook/ch29/format.php
explode: Asha | Bhopal | 82
implode: PHP - MySQLi - AJAX
str_split: ABC DEF GH
printf: Ravi scored 456 marks (91.2%)
sprintf: 00042 | left    |     3.14 | ff | 101
vsprintf: Neha is 23 years old
sscanf: roll=105, name=Kiran
parse_str: {"city":"Bhopal","pin":"462011"}
wordwrap: The quick brown
fox jumps over
the lazy dog
String Functions – Comparing
FunctionPurpose
strcmp(a, b)Compares two strings (case-sensitive); returns < 0, 0 or > 0.
strcasecmp(a, b)Case-insensitive comparison.
strncmp(a, b, n) / strncasecmp(a, b, n)Compares the first n characters (case-sensitive / insensitive).
strnatcmp(a, b) / strnatcasecmp(a, b)"Natural order" comparison (case-sensitive / insensitive).
strcoll(a, b)Locale-based comparison.
similar_text(a, b [, &percent])Calculates the similarity of two strings.
levenshtein(a, b)Number of single-character edits between two strings.
soundex(string) / metaphone(string)Phonetic keys – words that sound alike get the same key.
File: htdocs/phpbook/ch29/compare.php
<?php
echo "strcmp('apple','Apple'): " . strcmp("apple", "Apple") . "<br>";
echo "strcasecmp('apple','Apple'): " . strcasecmp("apple", "Apple") . "<br>";
echo "strncmp('PHP8','PHP7',3): " . strncmp("PHP8", "PHP7", 3) . "<br>";
echo "strcmp vs strnatcmp ('img2','img10'): " . strcmp("img2", "img10") . " / " . strnatcmp("img2", "img10") . "<br>";
similar_text("World", "Word", $pct);
echo "similar_text('World','Word'): " . round($pct, 1) . "%<br>";
echo "levenshtein('kitten','sitting'): " . levenshtein("kitten", "sitting") . "<br>";
echo "soundex: Robert=" . soundex("Robert") . ", Rupert=" . soundex("Rupert") . "<br>";
echo "metaphone('Thompson'): " . metaphone("Thompson");
?>
OUTPUT browser · http://localhost/phpbook/ch29/compare.php
strcmp('apple','Apple'): 32
strcasecmp('apple','Apple'): 0
strncmp('PHP8','PHP7',3): 0
strcmp vs strnatcmp ('img2','img10'): 1 / -1
similar_text('World','Word'): 88.9%
levenshtein('kitten','sitting'): 3
soundex: Robert=R163, Rupert=R163
metaphone('Thompson'): 0MPSN
String Functions – HTML, Encoding and Hashing
FunctionPurpose
htmlspecialchars(string [, flags])Converts & " ' < > into HTML entities.
htmlentities(string [, flags])Converts all applicable characters into HTML entities.
html_entity_decode(string) / htmlspecialchars_decode(string)Converts entities back to characters.
get_html_translation_table([table])Returns the translation table used by the two functions above.
strip_tags(string [, allowed])Removes HTML and PHP tags.
addslashes(string) / stripslashes(string)Adds / removes backslashes before quotes and backslashes.
addcslashes(string, chars) / stripcslashes(string)C-style escaping of given characters / un-escaping.
quotemeta(string)Escapes the meta characters . \ + * ? [ ^ ] $ ( ).
chr(code) / ord(char)Character of an ASCII code / ASCII code of the first character.
bin2hex(string) / hex2bin(string)Converts binary data to hexadecimal and back.
base64_encode / base64_decodeBase64 encoding and decoding.
urlencode / urldecode / rawurlencodeURL encoding and decoding.
str_rot13(string)ROT13 encoding.
convert_uuencode / convert_uudecodeuuencode encoding and decoding.
quoted_printable_decode / quoted_printable_encodeQuoted-printable decoding and encoding.
md5(string) / md5_file(file)MD5 hash (32 hex characters) – not for passwords.
sha1(string) / sha1_file(file)SHA-1 hash (40 hex characters) – not for passwords.
crc32(string)32-bit CRC checksum.
hash(algorithm, data)Hash with any algorithm, e.g. sha256.
crypt(string, salt)One-way hashing (PHP 8: the salt is required).
password_hash(password, algo) / password_verify(password, hash)The correct way to store and check passwords.
File: htdocs/phpbook/ch29/encode.php
<?php
$html = "<b>Tom & Jerry's</b> \"show\"";
echo "htmlspecialchars: " . htmlspecialchars(htmlspecialchars($html)) . "<br>";
echo "strip_tags: " . strip_tags($html) . "<br>";
echo "addslashes: " . addslashes("It's \"PHP\"") . "<br>";
echo "chr(65) = " . chr(65) . ", ord('a') = " . ord("a") . "<br>";
echo "bin2hex('PHP'): " . bin2hex("PHP") . "<br>";
echo "base64_encode('PHP 8'): " . base64_encode("PHP 8") . " → " . base64_decode("UEhQIDg=") . "<br>";
echo "urlencode('a b&c=d'): " . urlencode("a b&c=d") . "<br>";
echo "str_rot13('Hello'): " . str_rot13("Hello") . "<br>";
echo "md5('php'): " . md5("php") . "<br>";
echo "sha1('php'): " . sha1("php") . "<br>";
echo "hash('sha256','php'): " . substr(hash("sha256", "php"), 0, 32) . "…<br>";
echo "crc32('php'): " . crc32("php") . "<br>";
$h = password_hash("Secret@123", PASSWORD_DEFAULT);
echo "password_hash length: " . strlen($h) . ", starts with " . substr($h, 0, 4) . "<br>";
echo "password_verify: " . var_export(password_verify("Secret@123", $h), true);
?>
OUTPUT browser · http://localhost/phpbook/ch29/encode.php
htmlspecialchars: &lt;b&gt;Tom &amp; Jerry&#039;s&lt;/b&gt; &quot;show&quot;
strip_tags: Tom & Jerry's "show"
addslashes: It\'s \"PHP\"
chr(65) = A, ord('a') = 97
bin2hex('PHP'): 504850
base64_encode('PHP 8'): UEhQIDg= → PHP 8
urlencode('a b&c=d'): a+b%26c%3Dd
str_rot13('Hello'): Uryyb
md5('php'): e1bfd762321e409cee4ac0b6e841963c
sha1('php'): 47425e4490d1548713efea3b8a6f5d778e4b1766
hash('sha256','php'): 12a5d18ee896e59954bdce0f4acc7212…
crc32('php'): 1452351953
password_hash length: 60, starts with $2y$
password_verify: true

Never store passwords with md5() or sha1() – they are fast and can be cracked. Use password_hash() and password_verify() (Chapter 36 and the project use them).

String functions removed from PHP
FunctionRemoved inUse instead
ereg(), eregi()PHP 7.0preg_match() with the i flag
ereg_replace(), eregi_replace()PHP 7.0preg_replace()
split(), spliti()PHP 7.0preg_split() or explode()
sql_regcase()PHP 7.0preg_match() with the i flag
money_format()PHP 8.0number_format() or NumberFormatter
convert_cyr_string()PHP 8.0mb_convert_encoding() or iconv()
hebrevc()PHP 8.0nl2br(hebrev($text))
fgetss()PHP 8.0strip_tags(fgets($h))
utf8_encode(), utf8_decode()deprecated 8.2mb_convert_encoding()
Variable Functions
FunctionPurpose
isset(var, ...)Checks whether a variable is set and not null.
empty(var)Checks whether a variable is empty ("", 0, "0", null, false, []) or not set.
unset(var, ...)Destroys the variable.
is_null(var)Checks whether a variable is null.
gettype(var) / get_debug_type(var)Returns the type of a variable (get_debug_type(): PHP 8 names such as int).
settype(&var, type)Sets the type of a variable.
intval(var [, base])Integer value of a variable (optionally from another base).
floatval(var)Float value. doubleval() is an alias.
strval(var) / boolval(var)String / boolean value of a variable.
is_int / is_integer / is_long (var)Checks whether a variable is an integer.
is_float / is_double (var)Checks whether a variable is a float.
is_string / is_bool / is_array / is_object / is_resource / is_iterable / is_countable (var)Type checks.
is_numeric(var)Checks whether a variable is a number or a numeric string.
is_scalar(var)Checks whether it is int, float, string or bool.
is_callable(var)Checks whether it can be called as a function.
print_r(var [, return])Prints human-readable information about a variable.
var_dump(var, ...)Dumps type and value information.
var_export(var [, return])Outputs or returns valid PHP code representing the variable.
serialize(value) / unserialize(string)Converts a value to a storable string and back.
get_defined_vars()Returns all defined variables of the current scope.
get_resource_type(handle)Returns the type of a resource.
is_real(var)Removed in PHP 8.0 – use is_float().
import_request_variables(types [, prefix])Removed in PHP 5.4 – read $_GET/$_POST.
File: htdocs/phpbook/ch29/variables.php
<?php
$values = [42, 3.5, "123", "12abc", "", null, true, [1, 2]];
foreach ($values as $v) {
    echo str_pad(var_export($v, true), 18) . " type=" . get_debug_type($v)
       . " numeric=" . var_export(is_numeric($v), true)
       . " empty=" . var_export(empty($v), true) . "<br>";
}
$x = "25.7 kg";
echo "intval: " . intval($x) . ", floatval: " . floatval($x) . ", intval('ff', 16): " . intval("ff", 16) . "<br>";
settype($x, "integer");
echo "after settype(integer): "; var_dump($x);
$data = ["name" => "Asha", "marks" => [82, 75]];
$ser = serialize($data);
echo "<br>serialize: $ser<br>";
echo "unserialize name: " . unserialize($ser)["name"] . "<br>";
echo "var_export: " . var_export(["a" => 1, "b" => true], true);
?>
OUTPUT browser · http://localhost/phpbook/ch29/variables.php
42 type=int numeric=true empty=false
3.5 type=float numeric=true empty=false
'123' type=string numeric=true empty=false
'12abc' type=string numeric=false empty=false
'' type=string numeric=false empty=true
NULL type=null numeric=false empty=true
true type=bool numeric=false empty=false
array ( 0 => 1, 1 => 2, ) type=array numeric=false empty=false
intval: 25, floatval: 25.7, intval('ff', 16): 255
after settype(integer): int(25)
serialize: a:2:{s:4:"name";s:4:"Asha";s:5:"marks";a:2:{i:0;i:82;i:1;i:75;}}
unserialize name: Asha
var_export: array ( 'a' => 1, 'b' => true, )
Miscellaneous Functions
FunctionPurpose
define(name, value) / defined(name) / constant(name)Defines a constant / checks it exists / returns its value (also with a dynamic name).
die(message) / exit([status])Outputs a message and ends the script.
eval(code)Evaluates a string as PHP code – dangerous with user input.
sleep(seconds) / usleep(microseconds) / time_nanosleep(s, ns)Delays execution.
uniqid([prefix, more_entropy])Generates a unique id based on the current time in microseconds.
highlight_string(code [, return])Syntax-highlights a string of PHP code.
highlight_file(file [, return])Syntax-highlights a file. show_source() is an alias.
php_strip_whitespace(file)Returns the source of a file without comments and white space.
pack(format, values...) / unpack(format, data)Packs data into a binary string / unpacks it.
connection_aborted() / connection_status()Checks whether the client disconnected / the connection status.
ignore_user_abort([enable])Lets a script continue if the user aborts the connection.
get_browser([user_agent])Information about the browser's capabilities (needs a browscap file configured in php.ini).
php_check_syntax(file)Removed in PHP 5.0.5 – run php -l file.php in the XAMPP Shell.
connection_timeout()Removed long ago – use connection_status().
File: htdocs/phpbook/ch29/misc.php
<?php
define("COURSE", "PHP Basics to Advance");
$name = "COURSE";
echo "constant('$name'): " . constant($name) . ", defined: " . var_export(defined("COURSE"), true) . "<br>";
$id1 = uniqid(); $id2 = uniqid("INV-");
echo "uniqid lengths: " . strlen($id1) . " and " . strlen($id2) . " (prefix " . substr($id2, 0, 4) . ")<br>";
$start = microtime(true);
usleep(200000);                       // 0.2 seconds
echo "usleep(200000) took about " . round(microtime(true) - $start, 1) . " s<br>";
$bin = pack("nvN", 258, 258, 1);
echo "pack('nvN') length: " . strlen($bin) . " bytes, hex: " . bin2hex($bin) . "<br>";
print_r(unpack("nbig/vlittle/Nlong", $bin));
echo "<br>connection_status(): " . connection_status() . " (0 = normal)<br>";
echo "highlight_string:<br>";
highlight_string('<?php echo "Hello"; // greet ?>');
?>
OUTPUT browser · http://localhost/phpbook/ch29/misc.php
constant('COURSE'): PHP Basics to Advance, defined: true
uniqid lengths: 13 and 17 (prefix INV-)
usleep(200000) took about 0.2 s
pack('nvN') length: 8 bytes, hex: 0102020100000001
Array ( [big] => 258 [little] => 258 [long] => 1 )
connection_status(): 0 (0 = normal)
highlight_string:

<?php echo "Hello"; // greet ?>
Key Takeaways
  • Strings: length/case (strlen, ucwords), search (strpos, strstr, str_contains), replace (str_replace, substr_replace, strtr), split/join (explode, implode, str_split), format (printf, sprintf, number_format), compare (strcmp, strnatcmp, similar_text, levenshtein).
  • Encoding: htmlspecialchars, strip_tags, base64_*, urlencode; hashing: md5, sha1, hash – but password_hash() for passwords.
  • ereg*, split, money_format and other old functions were removed; use preg_*, explode, number_format.
  • Variable functions test (isset, empty, is_*) and convert (intval, settype, serialize) values.
  • Miscellaneous: constants, exit, uniqid, sleep, highlight_string, pack/unpack.
Program File

Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch29 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.

Question / Answer (15 questions)

Answer : strlen() returns the number of bytes (characters) in a string; str_word_count() returns the number of words.

Answer : Both return the position of the first occurrence of a substring; strpos() is case-sensitive, stripos() is case-insensitive.

Answer : Because the substring may be found at position 0, which is falsy; comparing with != false or using it directly in if would wrongly treat a match at the start as "not found".

Answer : str_replace() replaces every occurrence of a search string; substr_replace() replaces the part of a string starting at a given position and length.

Answer : explode(",", $s) splits a string into an array at each separator; implode(",", $a) joins array elements into a string with the glue.

Answer : printf() outputs the formatted string directly; sprintf() returns it so that it can be stored or processed further.

Answer : A negative number if the first string is less than the second, 0 if they are equal, and a positive number if it is greater (case-sensitive).

Answer : They measure how alike two strings are – levenshtein() counts the edits needed to turn one into the other, similar_text() returns the number of matching characters and a percentage – useful for "did you mean" suggestions.

Answer : htmlspecialchars() converts special characters into entities so tags are displayed as text; strip_tags() removes the tags completely.

Answer : MD5 (and SHA-1) are fast and unsalted, so passwords can be cracked by brute force or rainbow tables. Use password_hash() to store and password_verify() to check passwords.

Answer : The POSIX regular-expression functions ereg(), eregi(), ereg_replace(), eregi_replace(), split(), spliti() and sql_regcase(); use the preg_* functions instead.

Answer : isset() is true if the variable exists and is not null; empty() is true if the variable does not exist or has an "empty" value such as "", 0, "0", null, false or an empty array.

Answer : Converting a PHP value (e.g. an array or object) into a storable string with serialize(), and restoring it later with unserialize().

Answer : print_r() prints a readable structure; var_dump() also shows types and lengths; var_export() outputs valid PHP code that recreates the value.

Answer : A unique identifier based on the current time in microseconds (13 hex characters, optionally with a prefix and extra entropy); it is used for file names, order numbers and similar ids – not for security tokens.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. Which function splits a string into an array by a separator?

Show Answer

Correct Answer : B. explode()
explode() returns an array of pieces.

Q2. strcmp("apple", "apple") returns:

Show Answer

Correct Answer : C. 0
Equal strings give 0.

Q3. Which function should be used to store a password?

Show Answer

Correct Answer : C. password_hash()
password_hash() creates a salted, slow hash.

Q4. Which function was removed in PHP 7.0?

Show Answer

Correct Answer : C. split()
split() was one of the removed POSIX regex functions.

Q5. empty("0") returns:

Show Answer

Correct Answer : A. true
The string "0" counts as empty.

Bibliography/References

The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.

  1. The PHP Group. (n.d.). PHP Manual – String Functions. https://www.php.net/manual/en/ref.strings.php
  2. The PHP Group. (n.d.). PHP Manual – Variable handling Functions. https://www.php.net/manual/en/ref.var.php
  3. The PHP Group. (n.d.). PHP Manual – Misc. Functions. https://www.php.net/manual/en/ref.misc.php
  4. The PHP Group. (n.d.). PHP Manual – Password Hashing. https://www.php.net/manual/en/book.password.php
  5. The PHP Group. (n.d.). PHP Manual – Deprecated features in PHP 8.2. https://www.php.net/manual/en/migration82.deprecated.php