Web-related tasks often involve text manipulation and PHP has many functions to help. PHP’s string type offers a flexible and powerful means of working with text. In this article, you’ll learn nine PHP string functions that you must learn today.
What are String Functions?
String functions are the built-in functions that help you to manipulate strings. You will typically call them by passing a PHP string variable for the function to operate on. Take a look at the example below. The strlen() function calculates the length of the string.
Output:
1. implode()
The implode() function converts an array of strings to a single string and returns it. This function accepts two parameters: the separator and the array of strings. Let’s understand implode using an example:
Output:
2. ord()
The ord() function returns the ASCII value of the character passed to it.
Output:
3. chr()
The chr() function is the opposite of ord. It returns the corresponding character when you pass its ASCII value. The ASCII value can be decimal, hexadecimal, or octal.
Output:
4. md5()
The md5() function converts the given string to its MD5 hash. This function accepts two parameters: the string and a boolean parameter specifying the output format. By default, the output is a string containing 32 hexadecimal characters. If you want the output in binary form, pass true as the value of the second parameter.
Output:
5. chop()
The chop() function removes whitespace, or other characters, from the end of the given string. It accepts two parameters: the string variable and the characters you want to delete from it.
Output:
6. strcmp()
The strcmp() function compares two strings and returns a value accordingly. This function accepts two string arguments. If the two strings are equal, it will return 0. If the first string is less than the second, it will return a negative value. Otherwise, it returns a positive value.
Output:
7. strrev()
The strrev() function reverses the string.
Output
8. ucfirst() & ucwords()
The ucfirst() function converts the first character of the string to uppercase. The ucwords() function converts the first character of all the words in a string variable to uppercase.
Output:
9. bin2hex() & hex2bin()
The bin2hex() function converts ASCII characters to their hexadecimal values. The hex2bin() function does the opposite.
Output:
What’s Next After Learning the Basics of PHP?
You have learned to manipulate strings in PHP using some of its built-in functions. What’s next? After learning the core concepts of any programming language, you should start practicing by building small projects. Building projects will improve your coding skills and help you get a good grasp of the language.
Looking for a good starting project using PHP? Authentication is a common task which you can use to learn more about PHP and MYSQL integration.