Php

Arrays and Functions

Arrays in PHP

An array is a variable that can hold multiple values.


1. Indexed Arrays

Values stored with numeric keys.

php
$fruits = ["apple", "banana", "cherry"];

echo $fruits[0]; // Output: apple

Or using array():

php
$colors = array("red", "green", "blue");

2. Associative Arrays

Values stored with custom keys.

php
$person = [
"name" => "Alice",
"age" => 28,
"city" => "New York"
];

echo $person["name"]; // Output: Alice


3. Multidimensional Arrays

Arrays within arrays.

php
$users = [
["name" => "John", "age" => 30],
["name" => "Jane", "age" => 25]
];

echo $users[1]["name"]; // Output: Jane


4. Useful Array Functions

Function Description
count() Get the number of elements
array_push() Add item(s) to end of array
array_pop() Remove last element
array_keys() Get all keys
in_array() Check if a value exists
sort() Sort array in ascending order
asort() Sort associative array by value
php
$numbers = [5, 3, 9];
sort($numbers); // [3, 5, 9]

Functions in PHP

Functions help you reuse blocks of code.


1. Defining a Function

php
function greet() {
echo "Hello!";
}

greet(); // Output: Hello!


2. Functions with Parameters

php
function greetUser($name) {
echo "Hello, $name!";
}

greetUser("Sara"); // Output: Hello, Sara!


3. Functions with Return Values

php
function add($a, $b) {
return $a + $b;
}

$sum = add(3, 5);
echo $sum; // Output: 8


4. Passing Arrays to Functions

php
function printItems($items) {
foreach ($items as $item) {
echo $item . "<br>";
}
}

$shoppingList = ["milk", "bread", "eggs"];
printItems($shoppingList);


5. Default Parameters

php
function sayHi($name = "Guest") {
echo "Hi, $name!";
}

sayHi(); // Output: Hi, Guest!
sayHi("Alex"); // Output: Hi, Alex!


Summary

Feature Description
Indexed array Uses numeric indexes
Assoc. array Uses named keys
Function Reusable block of code
Return Send a result back from a function
Array + Func Combine both to handle lists flexibly

Leave a Reply

Your email address will not be published. Required fields are marked *