Description
A developer's journey through code. I build, I break, and I write about it. Explore articles on modern software development, programming tips, and more.
As a PHP web developer, knowing the right PHP function to use in your code at any given time is a crucial skill for crafting dynamic and interactive web applications. PHP, a powerful server-side scripting language, whether you are working with user inputs, database queries, or crafting the output for your web pages, understanding these functions can significantly enhance your coding capabilities.
In this article, we will look into the intricacies of PHP's 56 frequently used functions. From determining the length of a string to performing advanced regular expression matches, each function serves a unique purpose. Join me on a journey through practical examples and detailed explanations that will empower you to wield these tools with confidence, making your PHP development endeavors more efficient and robust.
String manipulation in PHP involves various functions that allow you to perform operations on strings, such as finding the length, changing case, extracting substrings, and more. Here is an explanation of each function along with examples:
1. strlen: Returns the length of a string.
$str = "Hello, World!";
$length = strlen($str);
echo "Length of the string: $length"; // Output: Length of the string: 13
2. trim: Removes whitespace from the beginning and end of a string.
$str = " Trim me! ";
$trimmed = trim($str);
echo "Trimmed string: '$trimmed'"; // Output: Trimmed string: 'Trim me!'
3. strtolower: Converts a string to lowercase.
$str = "Convert Me";
$lowercase = strtolower($str);
echo "Lowercase string: '$lowercase'"; // Output: Lowercase string: 'convert me'
4. strtoupper: Converts a string to uppercase.
$str = "Convert Me";
$uppercase = strtoupper($str);
echo "Uppercase string: '$uppercase'"; // Output: Uppercase string: 'CONVERT ME'
5. substr: Extracts a substring from a string.
$str = "Hello, World!";
$substring = substr($str, 7, 5); // Start at position 7, extract 5 characters
echo "Substring: '$substring'"; // Output: Substring: 'World'
6. strpos: Finds the position of the first occurrence of a substring within a string.
$str = "Hello, World!";
$pos = strpos($str, "World");
echo "Position of 'World': $pos"; // Output: Position of 'World': 7
7. str_replace: Replaces occurrences of a substring with another string.
$str = "Hello, World!";
$newStr = str_replace("World", "Universe", $str);
echo "Replaced string: '$newStr'"; // Output: Replaced string: 'Hello, Universe!'
8. explode: Splits a string into an array by a delimiter.
$str = "Apple,Orange,Banana";
$arr = explode(",", $str);
print_r($arr); // Output: Array ( [0] => Apple [1] => Orange [2] => Banana )
9. implode: Joins array elements into a string using a delimiter.
$arr = array("Apple", "Orange", "Banana");
$str = implode(", ", $arr);
echo "Imploded string: '$str'"; // Output: Imploded string: 'Apple, Orange, Banana'
10. preg_match: Performs a regular expression match.
$str = "The quick brown fox";
if (preg_match("/brown/", $str)) {
echo "Match found!";
} else {
echo "No match found.";
}
// Output: Match found!
11. preg_replace: Performs a regular expression search and replace.
$str = "The quick brown fox";
$newStr = preg_replace("/brown/", "red", $str);
echo "Replaced string: '$newStr'"; // Output: Replaced string: 'The quick red fox'
12. md5, sha1: Calculate the MD5 or SHA1 hash of a string.
$str = "Password123";
$md5Hash = md5($str);
$sha1Hash = sha1($str);
echo "MD5 Hash: $md5Hash
";
echo "SHA1 Hash: $sha1Hash";
In PHP, arrays are versatile and widely used data structures that allow you to store and manipulate collections of data. The functions I have mentioned here provides various operations for working with arrays and other data structures. Let us go through each function and provide examples:
13. array_merge: Merges one or more arrays.
$array1 = array('a', 'b', 'c');
$array2 = array(1, 2, 3);
$result = array_merge($array1, $array2);
print_r($result);
Output:
Array
(
[0] => a
[1] => b
[2] => c
[3] => 1
[4] => 2
[5] => 3
)
14. array_keys: Returns all the keys of an array.
$array = array('name' => 'John', 'age' => 30, 'city' => 'New York');
$keys = array_keys($array);
print_r($keys);
Output:
Array
(
[0] => name
[1] => age
[2] => city
)
15. array_values: Returns all the values of an array.
$array = array('name' => 'John', 'age' => 30, 'city' => 'New York');
$values = array_values($array);
print_r($values);
Output:
Array
(
[0] => John
[1] => 30
[2] => New York
)
16. count: Counts the number of elements in an array or object.
$array = array('a', 'b', 'c');
$count = count($array);
echo $count; // Output: 3
17. in_array: Checks if a value exists in an array.
$array = array('a', 'b', 'c');
$exists = in_array('b', $array);
var_dump($exists); // Output: bool(true)
18. array_push: Inserts one or more elements onto the end of an array.
$array = array('a', 'b', 'c');
array_push($array, 'd');
print_r($array);
Output:
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)
19. array_pop: Removes and returns the last element from an array.
$array = array('a', 'b', 'c');
$lastElement = array_pop($array);
echo $lastElement; // Output: c
20. array_shift: Removes and returns the first element from an array.
$array = array('a', 'b', 'c');
$firstElement = array_shift($array);
echo $firstElement; // Output: a
21. array_unshift: Inserts one or more elements to the beginning of an array.
$array = array('b', 'c');
array_unshift($array, 'a');
print_r($array);
Output:
Array
(
[0] => a
[1] => b
[2] => c
)
22. isset: Checks if a variable is set and is not NULL.
$variable = 'some value';
if (isset($variable)) {
echo 'Variable is set.';
} else {
echo 'Variable is not set.';
}
23. empty: Checks if a variable is empty (NULL, 0, false, "", array() or unset).
$variable = '';
if (empty($variable)) {
echo 'Variable is empty.';
} else {
echo 'Variable is not empty.';
}
24. serialize: Converts a value to a storable string representation.
$data = array('name' => 'John', 'age' => 30);
$serializedData = serialize($data);
echo $serializedData;
25. unserialize: Converts a serialized string back into a PHP value.
$serializedData = 'a:2:{s:4:"name";s:4:"John";s:3:"age";i:30;}';
$data = unserialize($serializedData);
print_r($data);
Output:
Array
(
[name] => John
[age] => 30
)
The Numbers and Math functions in PHP programming provide a set of operations for working with numbers and performing mathematical calculations. Let us go through each function mentioned:
26. abs: Returns the absolute value of a number.
$num = -5;
$absValue = abs($num);
echo "Absolute value of $num is: $absValue"; // Output: Absolute value of -5 is: 5
27. round: Rounds a number to a specified number of decimal places.
$num = 3.14159;
$roundedNum = round($num, 2);
echo "Rounded value of $num to 2 decimal places is: $roundedNum"; // Output: Rounded value of 3.14159 to 2 decimal places is: 3.14
28. floor: Rounds a number down to the nearest integer.
$num = 4.8;
$floorValue = floor($num);
echo "Floor value of $num is: $floorValue"; // Output: Floor value of 4.8 is: 4
29. ceil: Rounds a number up to the nearest integer.
$num = 4.1;
$ceilValue = ceil($num);
echo "Ceil value of $num is: $ceilValue"; // Output: Ceil value of 4.1 is: 5
30. max: Returns the largest value from a list of numbers.
$numbers = array(10, 5, 8, 12, 7);
$maxValue = max($numbers);
echo "The largest value is: $maxValue"; // Output: The largest value is: 12
31. min: Returns the smallest value from a list of numbers.
$numbers = array(10, 5, 8, 12, 7);
$minValue = min($numbers);
echo "The smallest value is: $minValue"; // Output: The smallest value is: 5
32. rand: Generates a random number.
$randomNum = rand(1, 100);
echo "Random number between 1 and 100 is: $randomNum";
33. pow: Returns the base raised to the exponent power.
$base = 2;
$exponent = 3;
$result = pow($base, $exponent);
echo "$base raised to the power of $exponent is: $result"; // Output: 2 raised to the power of 3 is: 8
34. sqrt: Returns the square root of a number.
$num = 25;
$sqrtValue = sqrt($num);
echo "Square root of $num is: $sqrtValue"; // Output: Square root of 25 is: 5
35. log, exp: Returns the natural logarithm or exponential of a number.
$num = 2.71828;
$logValue = log($num);
$expValue = exp($num);
echo "Natural logarithm of $num is: $logValue, Exponential of $num is: $expValue";
36. sin, cos, tan, asin, acos, atan: Trigonometric functions.
$angle = 45;
$sinValue = sin(deg2rad($angle)); // Convert degrees to radians
$cosValue = cos(deg2rad($angle));
$tanValue = tan(deg2rad($angle));
echo "sin($angle) = $sinValue, cos($angle) = $cosValue, tan($angle) = $tanValue";
Note: When working with trigonometric functions, PHP functions like sin, cos, and tan usually expect the angle to be in radians, so it's a good practice to use deg2rad() to convert degrees to radians before passing them to these functions.
Dates and times can be manipulated and formatted using various functions. The functions I mentioned are part of the PHP date and time functionality, and they serve different purposes. Let us go through each one:
37. date(): The date() function is used to format a date or time according to a specified format.
$currentDate = date("Y-m-d H:i:s");
echo $currentDate;
This will output the current date and time in the format "Year-Month-Day Hour:Minute:Second."
38. time(): The time() function returns the current Unix timestamp, which represents the current date and time as the number of seconds since the Unix Epoch (January 1, 1970).
$timestamp = time();
echo $timestamp;
This will output the current Unix timestamp.
39. mktime(): The mktime() function is used to create a Unix timestamp from a given date and time.
$timestamp = mktime(12, 30, 0, 1, 1, 2024);
echo $timestamp;
This will output the Unix timestamp for January 1, 2024, 12:30 PM.
40. strftime(): The strftime() function is used to format a local time or date according to a specified format.
setlocale(LC_TIME, 'en_US'); // Set the locale to English
$formattedDate = strftime("%A, %B %d, %Y %H:%M:%S");
echo $formattedDate;
This will output the formatted date and time, including the day of the week, month, day, year, and time.
41. strtotime(): The strtotime() function parses a date/time string and returns a Unix timestamp.
$dateString = "2024-01-01";
$timestamp = strtotime($dateString);
echo $timestamp;
This will output the Unix timestamp for January 1, 2024, 00:00:00.
In PHP, input and output operations primarily involve interactions with the user through the browser or reading/writing data to files. The functions mentioned fall into these categories:
42. echo, print (Output data to the browser): echo and print are used to output data to the browser.
$message = "Hello, World!";
echo $message; // Outputs: Hello, World!
print $message; // Outputs: Hello, World!
43. die, exit (Terminates the script execution): die and exit are used to terminate the script execution.
$error_message = "Error: Something went wrong!";
die($error_message); // Terminates script and outputs the error message
// Alternatively: exit($error_message);
44. header (Sends a raw HTTP header): header is used to send raw HTTP headers to the browser.
header("Location: https://www.example.com"); // Redirects to the specified URL
45. file_get_contents (Reads the entire contents of a file into a string): file_get_contents is used to read the contents of a file into a string.
$file_content = file_get_contents("example.txt");
echo $file_content; // Outputs the content of example.txt
46. file_put_contents (Writes a string to a file): file_put_contents is used to write a string to a file.
$content_to_write = "This is some content.";
file_put_contents("output.txt", $content_to_write);
// Writes $content_to_write to output.txt
Control flow in PHP involves the use of conditional statements, loops, and control structures to determine the execution path of a program. Let us break down the key elements mentioned below.
47. if, else, elseif: These conditional statements allow you to execute different blocks of code based on whether a given condition is true or false.
$number = 10;
if ($number > 0) {
echo "The number is positive.";
} elseif ($number < 0) {
echo "The number is negative.";
} else {
echo "The number is zero.";
}
48. while, do, for: Loops allow you to repeatedly execute a block of code as long as a certain condition is true.
While loop:
$counter = 1;
while ($counter <= 5) {
echo "Iteration: $counter
";
$counter++;
}
Do-while loop:
$counter = 1;
do {
echo "Iteration: $counter
";
$counter++;
} while ($counter <= 5);
For loop:
for ($i = 1; $i <= 5; $i++) {
echo "Iteration: $i
";
}
49. break, continue: Controls loop execution.
break:
for ($i = 1; $i <= 10; $i++) {
if ($i == 6) {
break; // Exit the loop when $i is 6
}
echo $i . "
";
}
continue:
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue; // Skip iteration when $i is 3
}
echo $i . "
";
}
50. switch, case, default: The switch statement is used to perform different actions based on the value of a variable.
$day = "Monday";
switch ($day) {
case "Monday":
echo "It's the start of the week.";
break;
case "Friday":
echo "It's almost the weekend.";
break;
default:
echo "It's a regular day.";
}
In PHP, functions and classes are fundamental building blocks for organizing and structuring code.
51. Function and return: Function defines a function and return returns a value from a function.
function addNumbers($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$result = addNumbers(5, 7);
echo "Sum: $result"; // Output: Sum: 12
52. Class: Defines a class.
class Car {
// Properties
public $brand;
public $model;
// Constructor
public function __construct($brand, $model) {
$this->brand = $brand;
$this->model = $model;
}
// Method
public function displayInfo() {
echo "Car: {$this->brand} {$this->model}";
}
}
// Create an instance of the Car class
$myCar = new Car("Toyota", "Camry");
// Access class properties
echo $myCar->brand; // Output: Toyota
// Call class method
$myCar->displayInfo(); // Output: Car: Toyota Camry
53. Global: Declares a variable as global.
$globalVar = 10;
function accessGlobalVar() {
global $globalVar;
echo $globalVar;
}
accessGlobalVar(); // Output: 10
54. Static: Declares a variable as static.
function countCalls() {
static $count = 0;
$count++;
echo "Function called $count times.";
}
countCalls(); // Output: Function called 1 times.
countCalls(); // Output: Function called 2 times.
55. Var (deprecated): Declares a variable (deprecated). Note that the use of var to declare class properties is deprecated, and you should use public, protected, or private instead based on your visibility requirements.
class Example {
var $deprecatedVar; // Deprecated usage
}
56. basename: Returns the basename of a path.
$path = "/path/to/myfile.txt";
$filename = basename($path);
echo "Filename: $filename"; // Output: Filename: myfile.txt
In this example, the basename function is used to extract the filename (myfile.txt) from the given path (/path/to/myfile.txt). It is commonly used when you have a full path and want to get just the filename portion.
Cookies improve user experience on SunshineIHCTS. By continuing to use this website, you consent to the use of cookies in accordance with the Privacy policy.
A developer's journey through code. I build, I break, and I write about it. Explore articles on modern software development, programming tips, and more.
Comments section
You need to be logged in to comment, Login or Register.Approved comments:
VincenZöArt in 2024-04-04 12:43:23
I thought I know much PHP functions till I saw this, I know nothing 😂 thanks for listing all these Sir.
Reply You need to be logged in to reply to this comment, Login or Register.
David Scott in 2024-04-04 12:45:37
Learnt a lot from this, thank you.
Reply You need to be logged in to reply to this comment, Login or Register.
Arslan ahhmedt in 2024-10-30 21:21:30
Great article, the examples provided for each function made it easier to practice.
Reply You need to be logged in to reply to this comment, Login or Register.
_SunshineIHCTS in 2024-10-30 21:33:09
_I'm glad the article is useful, enjoy! 😊
Mbam Clinton in 2024-10-30 21:39:06
Is switch and if statement the same?
Reply You need to be logged in to reply to this comment, Login or Register.
_SunshineIHCTS in 2024-10-30 21:57:03
_ if statements allow you to execute blocks of code based on a given condition. While the switch statement is used to perform actions based on the value of a variable.
_David Scott in 2024-10-30 22:08:38
_I use the two almost the same way, it depends on what I want to do.
Dan Morehead in 2024-10-30 22:06:50
My new glossary, let me save offline.
Reply You need to be logged in to reply to this comment, Login or Register.