FahmidasClassroom

Learn by easy steps

Learning Objectives

After completing this tutorial, you will be able to:

• Understand the purpose of functions in PHP.

• Create user-defined functions.

• Pass arguments and return values from functions.

• Work with indexed, associative, and multidimensional arrays.

• Perform common string operations using PHP built-in functions.

• Develop reusable PHP programs using functions and arrays.

• Use AI tools to improve code quality and debugging.

Introduction

As PHP programs become larger, writing all the code in a single file becomes difficult to manage. Functions allow programmers to organize code into reusable blocks, making programs easier to understand and maintain.

Arrays enable us to store multiple values in a single variable instead of creating separate variables for each value. They are widely used in web applications for storing lists of products, students, courses, and many other collections of data.

Strings are another essential component of PHP programming. User names, email addresses, passwords, search keywords, and messages are all represented as strings. PHP provides many built-in functions for processing and manipulating strings efficiently.

In this tutorial, you will learn how to write reusable functions, manage collections of data using arrays, and manipulate text using PHP string functions.

Prerequisites

Before starting this tutorial, you should understand:

• Variables

• Data types

• Operators

• Conditional statements

• Loops

What is a Function?

A function is a reusable block of code that performs a specific task.

Instead of writing the same code multiple times, you write it once inside a function and call it whenever needed.

Advantages of functions include:

• Code reusability

• Better organization

• Easier debugging

• Improved readability

• Reduced code duplication

Creating a Function

Syntax:

function functionName()

{

// statements

}

Example:

<?php 
function welcome() 
{ 
      echo "Welcome to PHP Programming."; 
} 
welcome(); 
?>

Output:

Function with Parameters

Parameters allow values to be passed into a function.

Example:

<?php

function greet($name)
{
    echo "Hello " . $name;
}
greet("Jafar");

?>

Output:

Function with Multiple Parameters

<?php

function add($a, $b)
{
     echo $a + $b;
}
add(20, 15);

?>

Output:

Function with Return Value

A function can return a value using the return statement.

Example:

<?php

function square($number)
{
     return $number * $number;
}
$result = square(8);
echo $result;

?>

Output:

Default Parameter Values

PHP allows parameters to have default values.

Example:

<?php

function country($name = "Bangladesh")
{
     echo $name;
}
country();

?>

Output:

Variable Scope

Variables declared inside a function are local.

Example

<?php

function test()
{
     $x = 50;
     echo $x;
}
test();

?>

Variables declared outside the function are global.

Example:

<?php

$x = 100;
function showValue()
{
     global $x;
     echo $x;
}
showValue();

?>

Output:

100

What is an Array?

An array stores multiple values in a single variable.

Instead of writing

$student1 = "Rahim";
$student2 = "Karim";
$student3 = "Nadia";

We can write

$students = ["Rahim", "Karim", "Nadia"];

Indexed Array

An indexed array stores values using numeric indexes.

Example:

<?php

$colors = ["Red", "Green", "Blue"];
echo $colors[0];

?>

Output:

Loop through an indexed array

<?php

$colors = ["Red", "Green", "Blue"];
foreach($colors as $color)
{
     echo $color . "<br>";
}

?>

Output:

Associative Array

An associative array stores data as key-value pairs.

Example:

<?php

$student = [
"name" => "Ayesha",
"department" => "CSE",
"semester" => 5
];
echo $student["department"];

?>

Output:

Display all values

<?php

$student = [
"name" => "Ayesha",
"department" => "CSE",
"semester" => 5
];

foreach($student as $key => $value)
{
     echo $key . " : " . $value . "<br>";
}

?>

Output:

Multidimensional Array

A multidimensional array contains one or more arrays.

Example:

<?php

$students = [
["Rahim",85],
["Karim",90],
["Nadia",95]
];

echo $students[1][0];

?>

Output:

Common Array Functions

Count the number of elements

<?php 
$numbers = [10,20,30,40]; 
echo count($numbers); 
?>

Output:

4

Sort an array

<?php

$numbers = [30,10,50,20];
sort($numbers);
print_r($numbers);

?>

Search for a value

<?php

$subjects = ["PHP","HTML","CSS"];
if(in_array("PHP",$subjects))
{
     echo "Found";
}

?>

What is a String?

A string is a sequence of characters enclosed within quotation marks.

Example:

<?php

$name = "Learning PHP";
echo $name;

?>

String Length

The strlen() function returns the length of a string.

Example:

<?php

$text = "Programming";
echo strlen($text);

?>

Count Words

The str_word_count() function counts words.

Example:

<?php

$text = "PHP is easy to learn.";
echo str_word_count($text);

?>

Output:

5

Convert to Uppercase

<?php

echo strtoupper("php programming");

?>

Output:

PHP PROGRAMMING

Convert to Lowercase

<?php

echo strtolower("PHP PROGRAMMING");

?>

Output:

php programming

Replace Text

Example:

<?php

$text = "I love Java.";
echo str_replace("Java","PHP",$text);

?>

Extract a Portion of a String

Example:

<?php

$text = "Programming";
echo substr($text,0,7);

?>

Reverse a String

Example:

<?php

echo strrev("PHP");

?>

Remove Extra Spaces

Example:

<?php

$text = " PHP Programming ";
echo trim($text);

?>

Split a String

Example:

<?php

$subjects = explode(",", "PHP,HTML,CSS");
print_r($subjects);

?>

Join Array Elements

Example:

<?php

$subjects = ["PHP","HTML","CSS"];
echo implode(", ", $subjects);

?>

Example 1

Calculate Factorial Using a Function

<?php 
function factorial($n) 
{ 
      $fact = 1; 
      for($i=1;$i<=$n;$i++) 
      { 
           $fact *= $i; 
      } 
      return $fact; 
} 
echo factorial(5); 
?>

Output:

Example 2

Calculate Average Marks

<?php

$marks = [80,85,90,88,95];
$total = array_sum($marks);
$average = $total / count($marks);
echo $average;

?>

Output:

Example 3

Find the Largest Number

<?php

$numbers = [12,45,67,23,89];
echo max($numbers);

?>

 

Output:

Example 4

Count Vowels

<?php

$text = "Computer Science";
$count = 0;
$vowels = ['a','e','i','o','u','A','E','I','O','U'];
for($i=0;$i<strlen($text);$i++)
{
     if(in_array($text[$i],$vowels))
     {
          $count++;
     }
}
echo $count;
?>

Output:

Example 5

Student Information

<?php

function displayStudent($name,$department,$cgpa)
{
    echo "Name: ".$name."<br>";
    echo "Department: ".$department."<br>";
    echo "CGPA: ".$cgpa;
}

displayStudent("Nadia","CSE",3.90);

?>

Output:

Exercise:

Task 1:

Create an associative array containing your personal information.

Task 2:

Sort an array in ascending and descending order.

Task 3:

Count the number of words in a paragraph.

Task 4:

Replace one word with another in a sentence.

Try yourself:

  • Develop a student result system using associative arrays.
  • Build a menu-driven application using functions.
  • Develop a contact list using multidimensional arrays.