PHP Tutorials for Beginners

Introduction to PHP Functions

PHP functions are blocks of code that perform specific tasks. They help make your code reusable and organized. Functions in PHP can be built-in or user-defined.

Built-in PHP Functions

PHP offers a wide range of built-in functions to perform common tasks. Here are a few examples:

String Functions

                
                <?php
                // Example: strlen() function
                $text = "Hello, World!";
                echo strlen($text); // Output: 13
                ?>
                
            

Array Functions

                
                <?php
                // Example: array_push() function
                $array = array("Apple", "Banana");
                array_push($array, "Cherry");
                print_r($array); // Output: Array ( [0] => Apple [1] => Banana [2] => Cherry )
                ?>
                
            

Creating Custom PHP Functions

You can create your own functions to encapsulate reusable code. Here’s a basic example:

                
                <?php
                // User-defined function
                function greet($name) {
                    return "Hello, " . $name . "!";
                }
                
                echo greet("John"); // Output: Hello, John!
                ?>
                
            

Function Parameters and Return Values

Functions can accept parameters and return values. Here’s how you can use them:

                
                <?php
                // Function with parameters and return value
                function calculateArea($width, $height) {
                    return $width * $height;
                }
                
                echo calculateArea(5, 10); // Output: 50
                ?>
                
            

Further Reading

For more advanced topics and best practices in PHP functions, check out the following resources: