8 Essential Built‑in PHP Functions Every Developer Should Know
This article presents eight essential built‑in PHP functions—including variable‑argument handling, file searching with glob(), memory and CPU usage monitoring, system constants, unique ID generation, serialization, and string compression—complete with clear code examples to help developers write more efficient PHP code.
PHP developers benefit from many built‑in functions; mastering them can make development smoother. This article shares eight indispensable PHP functions with practical code examples.
1. Variable number of function arguments
PHP allows functions to accept any number of arguments, unlike the fixed‑parameter style of .NET or Java. The example below shows a function with default parameters and how to call it.
// Two default parameters
def function foo($arg1 = "", $arg2 = "") {
echo "arg1:$arg1
";
echo "arg2:$arg2
";
}
foo('hello','world'); // outputs: arg1: hello
arg2: world
foo(); // outputs: arg1:
arg2:The following demonstrates PHP’s variadic arguments using func_get_args():
// No formal parameters
function foo() {
$args = func_get_args();
foreach ($args as $k => $v) {
echo "arg".($k+1).":$v
";
}
}
foo(); // no output
foo('hello'); // outputs: arg1: hello
foo('hello','world','again'); // outputs: arg1: hello
arg2: world
arg3: again2. Using glob() to find files
The glob() function works like scandir() to locate files matching a pattern.
// Find all PHP files in the current directory
$files = glob('*.php');
print_r($files);
/* Example output:
Array
(
[0] => phptest.php
[1] => pi.php
[2] => post_output.php
[3] => test.php
)
*/
// Find PHP and TXT files using braces
$files = glob('*.{php,txt}', GLOB_BRACE);
print_r($files);
/* Example output includes both .php and .txt files */You can also include a path or retrieve absolute paths:
// Search in a subdirectory
$files = glob('../images/a*.jpg');
print_r($files);
/* Example output:
Array
(
[0] => ../images/apple.jpg
[1] => ../images/art.jpg
)
*/
// Convert to absolute paths
$files = array_map('realpath', $files);
print_r($files);
/* Example output shows full filesystem paths */3. Getting memory usage information
PHP provides memory_get_usage() and memory_get_peak_usage() to monitor current and peak memory consumption.
echo "Initial: ".memory_get_usage()." bytes
"; // Initial: 361400 bytes
for ($i = 0; $i < 100000; $i++) {
$array[] = md5($i);
}
for ($i = 0; $i < 50000; $i++) {
unset($array[$i]);
}
echo "Final: ".memory_get_usage()." bytes
"; // Final: 885912 bytes
echo "Peak: ".memory_get_peak_usage()." bytes
"; // Peak: 13687072 bytes4. Getting CPU usage information
The getrusage() function returns an array with CPU usage statistics (not available on Windows).
print_r(getrusage());
/* Example output (truncated):
Array
(
[ru_utime.tv_sec] => 0
[ru_utime.tv_usec] => 0
[ru_stime.tv_sec] => 0
[ru_stime.tv_usec] => 6269
...
)
*/5. Accessing system constants
PHP defines useful constants such as __LINE__, __FILE__, __DIR__, __FUNCTION__, __CLASS__, __METHOD__, and __NAMESPACE__. They are handy for debugging and path handling.
// Relative include (may break when script is run from another directory)
require_once('config/database.php');
// Reliable include using __DIR__
require_once(dirname(__FILE__) . '/config/database.php');Example of using __LINE__ for debug output:
my_debug("some debug message", __LINE__);
// Output: Line 4: some debug message
my_debug("another debug message", __LINE__);
// Output: Line 11: another debug message
function my_debug($msg, $line) {
echo "Line $line: $msg
";
}6. Generating unique IDs
Instead of using md5() (which produces long, unordered strings), PHP’s uniqid() generates a short unique identifier.
// Generate a unique string
echo uniqid(); // e.g., 4bd67c947233e
// Generate another unique string
echo uniqid(); // e.g., 4bd67c94723407. Serialization
Use serialize() and unserialize() to store complex data structures in a string.
// Complex array
$myvar = array('hello', 42, array(1, 'two'), 'apple');
// Serialize
$string = serialize($myvar);
echo $string; // a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";}
// Unserialize
$newvar = unserialize($string);
print_r($newvar);
/* Example output:
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
*/8. String compression
PHP’s gzcompress() and gzuncompress() allow you to compress and decompress strings.
<?php
$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit...";
$compressed = gzcompress($string);
echo "Original size: ".strlen($string)."
"; // Original size: 800
echo "Compressed size: ".strlen($compressed)."
"; // Compressed size: 418
$original = gzuncompress($compressed);
?>By understanding and applying these built‑in functions, PHP developers can write cleaner, more efficient, and more maintainable code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
