0
0
PHPprogramming~5 mins

Function declaration and calling in PHP

Choose your learning style9 modes available
Introduction

Functions help you organize your code by grouping instructions together. You can run the same set of instructions many times without rewriting them.

When you want to repeat a task multiple times in your program.
When you want to break a big problem into smaller, manageable parts.
When you want to reuse code in different places without copying it.
When you want to make your code easier to read and understand.
Syntax
PHP
<?php
function functionName() {
    // code to run
}

functionName(); // calling the function
?>

Functions start with the keyword function followed by the name and parentheses.

To run the function, you write its name followed by parentheses.

Examples
This function prints 'Hello!' when called.
PHP
<?php
function sayHello() {
    echo "Hello!\n";
}

sayHello();
This function prints a morning greeting.
PHP
<?php
function greet() {
    echo "Good morning!\n";
}

greet();
Sample Program

This program defines a function that adds two numbers and prints the result. Then it calls the function to run it.

PHP
<?php
function addNumbers() {
    $sum = 5 + 3;
    echo "Sum is: $sum\n";
}

addNumbers();
OutputSuccess
Important Notes

Function names should be clear and describe what the function does.

Functions can be called many times after they are declared.

Summary

Functions group code to do a specific job.

Declare a function with function keyword and call it by its name.

Using functions makes your code cleaner and easier to manage.