PHP – Arrays, Functions and References
1. Arrays in PHP
An array is a collection of multiple values stored in a single variable.
Types of Arrays:
1. Indexed Array
2. Associative Array
3. Multidimensional Array
1.1 Indexed Array
Syntax:
$array = array("value1", "value2", "value3");
Example:
<?php
$colors = array("Red", "Green", "Blue");
echo $colors[0];
?>
Output:
Red
1.2 Associative Array
Syntax:
$array = array("key1"=>"value1", "key2"=>"value2");
Example:
<?php
$student = array("name"=>"Raj", "age"=>20);
echo $student["name"];
?>
Output:
Raj
1.3 Multidimensional Array
Example:
<?php
$marks = array("Amit" => array("Math"=>90, "English"=>85));
echo $marks["Amit"]["Math"];
?>
Output:
90
2. Functions in PHP
A function is a block of code that performs a specific task and can be reused.
2.1 User-defined Functions
Syntax:
function functionName(parameters){
// code
}
Example:
<?php
function greet($name){
return "Hello, " . $name;
}
echo greet("Mihir");
?>
Output:
Hello, Mihir
2.2 Functions with Default Parameter
Example:
<?php
function greet($name="Guest"){
echo "Welcome, " . $name;
}
greet();
?>
Output:
Welcome, Guest
2.3 Functions with Return Value
Example:
<?php
function add($a, $b){
return $a + $b;
}
echo add(10,20);
?>
Output:
30
3. References in PHP
A reference means two variables pointing to the same memory location.
3.1 Assign by Reference
Example:
<?php
$x = 10;
$y = &$x;
$y = 20;
echo $x;
?>
Output:
20
3.2 Pass by Reference in Functions
Example:
<?php
function addFive(&$num){
$num += 5;
}
$value = 10;
addFive($value);
echo $value;
?>
Output:
15
Summary
• Arrays: Store multiple values in one variable (Indexed, Associative, Multidimensional).
• Functions: Reusable block of code.
• References: Two variables share same memory.