1. php
  2. /basics
  3. /functions

Introduction to PHP functions

Definition

In PHP, a function is a block of code that can be reused multiple times throughout a script. Functions are defined using the "function" keyword, and can take one or more parameters (also known as arguments) as input. There are several types of functions in PHP including Built-in functions, User-defined functions

Functions are fundamental to programming because they:

  • Enable Code Reuse: Write once, use many times instead of duplicating code
  • Improve Organization: Break complex problems into smaller, manageable pieces
  • Enhance Maintainability: Changes in one place affect all uses of the function
  • Support Testing: Individual functions can be tested in isolation
  • Promote Abstraction: Hide implementation details behind a simple interface

Built-in functions

PHP comes with hundreds of built-in functions that provide ready-to-use functionality for common tasks. These functions are part of PHP's core and don't require any special installation or configuration. Understanding and using these functions effectively can dramatically improve your productivity and code quality.

Some common PHP Built-in functions include:

  1. array_merge() - This function merges one or more arrays together and returns a new array.
  2. count() - This function returns the number of elements in an array.
  3. in_array() - This function checks if a specific value exists in an array and returns a boolean value.
  4. sort() - This function sorts the elements in an array in ascending order.
  5. array_slice() - This function returns a portion of an array, specified by a start and end position.
  6. array_keys() - This function returns an array of all the keys in an associative array.
  7. array_values() - This function returns an array of all the values in an associative array.
  8. array_diff() - This function compares two or more arrays and returns an array of values that are present in the first array but not in the other arrays.
  9. array_intersect() - This function compares two or more arrays and returns an array of values that are present in all of the arrays.
  10. array_search() - This function searches for a specific value in an array and returns the key if found, otherwise returns false.

Examples of built-in functions

Let's explore each of these functions with practical examples and understand when to use them:

  1. array_merge()
$array1 = array("a" => "red", "b" => "green");
$array2 = array("c" => "blue", "d" => "yellow");
$result = array_merge($array1, $array2);
print_r($result);

Output:

Array ( [a] => red [b] => green [c] => blue [d] => yellow )

Understanding array_merge():

  • Combines Arrays: Creates a new array containing all elements from the input arrays
  • Reindexes Numeric Keys: Numeric keys are renumbered starting from 0
  • Preserves String Keys: Associative keys are maintained
  • Overwrites Duplicate Keys: Later values overwrite earlier ones for the same string key

Common use cases:

  • Combining configuration arrays
  • Merging default options with user-provided options
  • Concatenating multiple result sets
  • Building complete datasets from partial sources

Important notes:

  • Use the + operator to preserve numeric keys
  • For deep merging of nested arrays, use array_merge_recursive()
  • Performance: Creates a new array, so memory usage increases with array size
  1. count()
$fruits = array("apple", "banana", "orange", "mango");
echo count($fruits);

Output:

4

Understanding count():

  • Returns Element Count: Gives the total number of elements in an array or countable object
  • Works Recursively: Can count elements in multi-dimensional arrays with COUNT_RECURSIVE flag
  • Handles Objects: Works with objects implementing the Countable interface
  • Returns 0 for Non-Arrays: Safe to use with potentially null values

Best practices:

  • Cache count results in loops for better performance
  • Use empty() instead of count() == 0 for checking empty arrays
  • Be aware that count(null) returns 0, not an error
  1. in_array()
$fruits = array("apple", "banana", "orange", "mango");
if(in_array("banana", $fruits)) {
    echo "Banana is in the array.";
} else {
    echo "Banana is not in the array.";
}

Output:

Banana is in the array.

Understanding in_array():

  • Searches Values: Checks if a value exists anywhere in the array
  • Type Comparison: Use third parameter true for strict type checking
  • Case Sensitive: String comparisons are case-sensitive
  • Performance: Linear search, slower for large arrays

Important considerations:

// Loose comparison (default)
in_array("10", [10, 20, 30]); // true

// Strict comparison
in_array("10", [10, 20, 30], true); // false

// For better performance with large arrays, use array_flip() + isset()
$flipped = array_flip($large_array);
if (isset($flipped[$search_value])) {
    // Found
}
  1. sort()
$numbers = array(4, 2, 8, 3, 1, 5);
sort($numbers);
print_r($numbers);

Output:

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 8 )

Understanding sort():

  • In-Place Sorting: Modifies the original array rather than returning a new one
  • Reindexes Keys: Numeric keys are reset to 0, 1, 2, etc.
  • Multiple Sort Types: Use sort flags for different comparisons (SORT_NUMERIC, SORT_STRING)
  • Destroys Key Associations: Use asort() to preserve key-value associations

Related sorting functions:

  • rsort(): Reverse sort
  • asort(): Sort preserving keys
  • ksort(): Sort by keys
  • usort(): Sort using custom comparison function
  • natsort(): Natural order sorting
  1. array_slice()
$fruits = array("apple", "banana", "orange", "mango", "kiwi");
$slice = array_slice($fruits, 1, 3);
print_r($slice);

Output:

Array ( [0] => banana [1] => orange [2] => mango )

Understanding array_slice():

  • Extracts Portion: Returns a sequence of elements from an array
  • Preserves Keys: Use fourth parameter true to preserve original keys
  • Negative Offsets: Negative start counts from the end of array
  • Non-Destructive: Original array remains unchanged

Advanced usage:

// Get last 3 elements
$last_three = array_slice($fruits, -3);

// Get all except first 2
$skip_two = array_slice($fruits, 2);

// Preserve keys
$preserved = array_slice($fruits, 1, 3, true);
  1. array_keys()
$fruits = array("a" => "apple", "b" => "banana", "c" => "orange");
$keys = array_keys($fruits);
print_r($keys);

Output:

Array ( [0] => a [1] => b [2] => c )

Understanding array_keys():

  • Returns All Keys: Creates a new indexed array of all keys
  • Search Functionality: Can return keys for a specific value
  • Strict Comparison: Third parameter enables strict type checking
  • Useful for Iteration: Often used to iterate over associative arrays

Practical applications:

// Get keys for specific value
$colors = ["red" => "#FF0000", "green" => "#00FF00", "blue" => "#0000FF"];
$blue_keys = array_keys($colors, "#0000FF"); // ["blue"]

// Check if key exists
$all_keys = array_keys($array);
if (in_array("desired_key", $all_keys)) {
    // Key exists
}

These are just some examples of the many built-in functions that PHP provides, there are many more functions which can be used for various purposes such as handling files, HTTP, session, image processing, cryptography and other.

User Defined Functions

A custom function in PHP is a user-defined function, which means it is created by the user for specific purposes. Custom functions in PHP are created using the "function" keyword, followed by the function name, and a set of parentheses that may or may not contain parameters.

Creating your own functions is a crucial skill that allows you to:

  • Encapsulate Logic: Group related code together
  • Create Abstractions: Hide complex implementations behind simple interfaces
  • Build Libraries: Create reusable code modules
  • Improve Readability: Replace complex code blocks with descriptive function calls

The general syntax for creating a custom function in PHP is:

function function_name($parameter1, $parameter2, ...) {
    // code to be executed
}

Key components of a function:

  • Function Keyword: Tells PHP you're defining a function
  • Function Name: Should be descriptive and follow naming conventions
  • Parameters: Input values the function accepts (optional)
  • Function Body: The code that executes when function is called
  • Return Statement: Sends a value back to the caller (optional)

For example:

function add_numbers($x, $y) {
    return $x + $y;
}

This simple function demonstrates several important concepts:

  • Clear Purpose: The name clearly indicates what the function does
  • Parameters: Accepts two inputs that will be added
  • Return Value: Sends the result back to the caller
  • Reusability: Can be called multiple times with different values

Custom functions can also take default value for parameters and return statement can be used to return a value from the function after processing.

function greet_user($name = "Guest") {
    return "Hello, $name";
}

Default Parameters:

  • Provide fallback values when arguments aren't provided
  • Must come after required parameters
  • Make functions more flexible and easier to use
  • Common for configuration or optional features

Custom functions can be called from anywhere in the script by using the function name followed by parentheses containing any necessary arguments.

$result = add_numbers(5, 10);
echo $result; // will output 15

echo greet_user("John"); // will output "Hello, John"
echo greet_user(); // will output "Hello, Guest"

Advanced Function Features:

  1. Variable-Length Arguments:
function sum_all(...$numbers) {
    return array_sum($numbers);
}
echo sum_all(1, 2, 3, 4, 5); // 15
  1. Type Declarations (PHP 7+):
function calculate_discount(float $price, int $percentage): float {
    return $price * (1 - $percentage / 100);
}
  1. Anonymous Functions (Closures):
$greet = function($name) {
    return "Hello, $name!";
};
echo $greet("World"); // Hello, World!
  1. Return Type Declarations:
function get_user_data(): array {
    return ["name" => "John", "age" => 30];
}

Custom functions are useful because they allow you to modularize your code, making it more organized and easier to maintain. They also allow you to reuse code, reducing the amount of duplicated code in your scripts.

Best Practices

Following these best practices will help you write better, more maintainable functions:

  1. Use Clear and Descriptive Names: Function names should clearly indicate what they do. Use verbs for actions: calculateTotal(), validateEmail(), getUserData(). This makes code self-documenting.

  2. Proper Scoping: Use proper variable and function scoping to minimize the risk of naming conflicts. Understand the difference between local and global scope, and avoid polluting the global namespace.

  3. Type Safety: Use appropriate data types for function parameters and return values. In PHP 7+, use type declarations to catch errors early and improve code clarity.

  4. Documentation: Include clear and comprehensive documentation for each function, including details on its parameters, return values, and any exceptions that may be thrown. Use PHPDoc comments:

/**
 * Calculate the total price with tax
 * 
 * @param float $price Base price
 * @param float $taxRate Tax rate as decimal (0.1 for 10%)
 * @return float Total price including tax
 * @throws InvalidArgumentException If price or tax rate is negative
 */
function calculateTotalWithTax(float $price, float $taxRate): float {
    if ($price < 0 || $taxRate < 0) {
        throw new InvalidArgumentException("Price and tax rate must be positive");
    }
    return $price * (1 + $taxRate);
}
  1. Error Handling: Use appropriate error handling and validation to ensure that the function can handle unexpected input and return appropriate responses. Validate inputs early and fail fast.

  2. Consistent Style: Use consistent naming conventions and formatting to make the code more readable and maintainable. Follow PSR standards when possible.

  3. Avoid Global State: Avoid using global variables within functions, as this can make the function's behavior difficult to predict and understand. Pass needed values as parameters instead.

  4. Single Responsibility: Keep functions small and modular, breaking down large functions into smaller, more manageable units. Each function should do one thing well.

  5. Leverage Built-ins: Use built-in functions and libraries when available, rather than writing your own code to accomplish the same task. This reduces bugs and improves performance.

  6. Thorough Testing: Test functions thoroughly to ensure they are functioning as expected. Write unit tests for critical functions and test edge cases.