Working with Arrays in PHP
Working with Arrays in PHP
Arrays in PHP are essential for storing and managing multiple values efficiently. They allow
developers to organize data logically and manipulate it using loops and iterations.
$person = array("Name" => "John", "Age" => 30, "City" => "New York");
echo $person["Name"]; // Output: John
$students = array(
array("Alice", 22, "A"),
array("Bob", 21, "B"),
array("Charlie", 23, "A+")
);
echo $students[1][0]; // Output: Bob
$person = array("Name" => "John", "Age" => 30, "City" => "New York");
$i = 0;
do {
echo $numbers[$i] . "<br>";
$i++;
} while ($i < count($numbers));
Sorting Arrays
Counting Elements
if (array_key_exists("Age", $person)) {
echo "Key exists!";
}
Merging Arrays
Removing Elements
<?php
// Creating an indexed array
$fruits = array("Apple", "Banana", "Cherry", "Mango");
Output:
Fruits List:
Apple
Banana
Cherry
Mango
<?php
$numbers = array(10, 20, 30, 40, 50);
Output:
<?php
$values = array(5, 10, 2, 8, 15, 3);
$max = max($values);
$min = min($values);
Maximum Value: 15
Minimum Value: 2
4. Reverse an Array
<?php
$numbers = array(1, 2, 3, 4, 5);
Output:
Reversed Array: Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )
<?php
$values = array(10, 20, 10, 30, 40, 20, 50);
Output:
Unique Array: Array ( [0] => 10 [1] => 20 [3] => 30 [4] => 40 [6] => 50 )
<?php
$numbers = array(50, 20, 40, 10, 30);
echo "<br>";
Output:
Ascending Order: Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 [4] => 50 )
Descending Order: Array ( [0] => 50 [1] => 40 [2] => 30 [3] => 20 [4] => 10 )
<?php
$array1 = array("Red", "Green", "Blue");
$array2 = array("Yellow", "Pink", "Purple");
Output:
Merged Array: Array ( [0] => Red [1] => Green [2] => Blue [3] => Yellow [4] => Pink [5]
=> Purple )
<?php
$numbers = array(1, 2, 2, 3, 3, 3, 4, 4, 4, 4);
Output:
Frequency of elements:
1 occurs 1 times.
2 occurs 2 times.
3 occurs 3 times.
4 occurs 4 times.
9. Check if an Element Exists in an Array
<?php
$colors = array("Red", "Green", "Blue", "Yellow");
$search = "Green";
if (in_array($search, $colors)) {
echo "$search is present in the array.";
} else {
echo "$search is not present in the array.";
}
?>
Output:
<?php
$fruits = array("Apple", "Banana", "Cherry", "Mango");
// Remove "Banana"
unset($fruits[1]);
print_r($fruits);
?>
Output:
Array ( [0] => Apple [1] => Cherry [2] => Mango )
<?php
$colors = array("Red", "Blue", "Green", "Yellow");
$search = "Green";
if (in_array($search, $colors)) {
echo "$search is found in the array.";
} else {
echo "$search is not in the array.";
}
?>
Output:
PHP allows handling arrays in forms, processing user input, and performing various
operations with array functions.
Here’s an example where users enter their favorite fruits, and we store them in an array.
HTML Form:
<!DOCTYPE html>
<html>
<head>
<title>Favorite Fruits</title>
</head>
<body>
<form method="post">
Enter your favorite fruits (comma-separated):
<input type="text" name="fruits">
<input type="submit" name="submit" value="Submit">
</form>
<?php
if (isset($_POST['submit'])) {
$fruits = explode(",", $_POST['fruits']); // Convert input to an array
echo "<h3>Your Favorite Fruits:</h3>";
echo "<ul>";
foreach ($fruits as $fruit) {
echo "<li>" . trim($fruit) . "</li>";
}
echo "</ul>";
}
?>
</body>
</html>
Explanation:
Sorting an Array
<?php
$numbers = array(34, 12, 45, 78, 9);
sort($numbers); // Sort in ascending order
print_r($numbers);
?>
Output:
Array ( [0] => 9 [1] => 12 [2] => 34 [3] => 45 [4] => 78 )
<?php
$colors = array("Red", "Blue", "Green", "Yellow");
if (in_array("Green", $colors)) {
echo "Green is found in the array.";
}
?>
Output:
<?php
$values = array(10, 20, 30, 5, 40);
echo "Max: " . max($values) . "<br>";
echo "Min: " . min($values);
?>
Output:
Max: 40
Min: 5
<?php
$array1 = array("Apple", "Banana");
$array2 = array("Mango", "Orange");
$merged = array_merge($array1, $array2);
print_r($merged);
?>
Output:
Array ( [0] => Apple [1] => Banana [2] => Mango [3] => Orange )
Removing Duplicates
<?php
$numbers = array(10, 20, 10, 30, 20, 40);
$unique = array_unique($numbers);
print_r($unique);
?>
Output:
PHP provides the date() function and DateTime class to handle date and time operations.
<?php
echo "Today's Date: " . date("Y-m-d") . "<br>";
echo "Current Time: " . date("H:i:s") . "<br>";
?>
Output (Example):
<?php
echo "Formatted Date: " . date("l, F j, Y") . "<br>";
?>
Output:
<?php
echo "Current Timestamp: " . time();
?>
Output:
<?php
$timestamp = 1712063400;
echo "Date from Timestamp: " . date("Y-m-d H:i:s", $timestamp);
?>
Output:
<?php
$date1 = new DateTime("2025-01-01");
$date2 = new DateTime("2025-04-02");
$diff = $date1->diff($date2);
echo "Difference: " . $diff->days . " days";
?>
Output:
Difference: 91 days
<?php
date_default_timezone_set("Asia/Kolkata");
echo "Current Time in India: " . date("H:i:s");
?>
String manipulation is an essential part of PHP, allowing developers to create, access, and
modify strings efficiently. PHP provides various built-in functions to handle string
operations.
Creating a String
<?php
$name = "John Doe";
echo 'Hello, $name'; // Output: Hello, $name (does not parse variable)
echo "<br>";
echo "Hello, $name"; // Output: Hello, John Doe (parses variable)
?>
<?php
$str = "Hello";
echo $str[0]; // Output: H
echo "<br>";
echo $str[4]; // Output: o
?>
3. String Concatenation
Example:
<?php
$firstName = "John";
$lastName = "Doe";
<?php
$str = "Hello, World!";
echo strlen($str); // Output: 13
?>
<?php
$str = "PHP is a powerful scripting language";
echo str_word_count($str); // Output: 6
?>
c) Reversing a String
<?php
$str = "Hello";
echo strrev($str); // Output: olleH
?>
<?php
$str = "Welcome to PHP";
echo strpos($str, "PHP"); // Output: 11 (index starts from 0)
?>
<?php
$str = "I love PHP";
echo str_replace("PHP", "Python", $str); // Output: I love Python
?>
<?php
$str = "Hello World";
Example:
<?php
$str = "Hello, World!";
echo substr($str, 7, 5); // Output: World
?>
Example:
<?php
$str = " Hello World! ";
echo trim($str); // Output: "Hello World!"
?>
Example:
<?php
$str = "Learn PHP Programming";
if (strpos($str, "PHP") !== false) {
echo "PHP found in the string!";
} else {
echo "PHP not found.";
}
?>
Example:
<?php
$str = "Apple, Banana, Cherry";
$fruits = explode(", ", $str);
print_r($fruits);
?>
Output:
Array ( [0] => Apple [1] => Banana [2] => Cherry )
Example:
<?php
$fruits = array("Apple", "Banana", "Cherry");
$str = implode(" | ", $fruits);
Example:
<?php
$price = 50;
echo sprintf("The price is $%.2f", $price); // Output: The price is $50.00
?>
PHP provides powerful functions to search, replace, split, join, and manipulate strings
efficiently. Below are examples and explanations of key string operations.
The strpos() function is used to find the position of a substring in a string. It returns the
position (index) of the first occurrence or false if the substring is not found.
<?php
$str = "Welcome to PHP programming!";
$search = "PHP";
Output:
2. Replacing a Substring
<?php
$str = "I love PHP!";
$newStr = str_replace("PHP", "Python", $str);
echo $newStr;
?>
Output:
I love Python!
<?php
$str = "Apple, Banana, Cherry, Mango";
$fruits = explode(", ", $str);
print_r($fruits);
?>
Output:
Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Mango )
<?php
$str = "Hello";
$chunks = str_split($str, 2);
print_r($chunks);
?>
Output:
The implode() (or join()) function combines array elements into a string using a separator.
<?php
$fruits = array("Apple", "Banana", "Cherry", "Mango");
$str = implode(" | ", $fruits);
echo $str;
?>
Output:
PHP provides numerous built-in string functions. Here are some of the most commonly used
ones:
<?php
$str = "Hello, World!";
echo strlen($str); // Output: 13
?>
<?php
$str = "PHP is a powerful scripting language.";
echo str_word_count($str); // Output: 6
?>
c) Reversing a String
<?php
$str = "Hello";
echo strrev($str); // Output: olleH
?>
<?php
$str = "Hello World";
e) Extracting a Substring
<?php
$str = "Welcome to PHP";
echo substr($str, 11, 3); // Output: PHP
?>
<?php
$str = " Hello World! ";
echo trim($str); // Output: "Hello World!"
?>
<?php
$price = 50;
echo sprintf("The price is $%.2f", $price);
?>
Output:
PHP does not have built-in functions for this, but you can use strpos() and substr().
<?php
$str = "Hello, welcome to PHP!";
if (strpos($str, "Hello") === 0) {
echo "The string starts with 'Hello'.";
}
?>
<?php
$str = "Hello, welcome to PHP!";
if (substr($str, -3) === "PHP") {
echo "The string ends with 'PHP'.";
}
?>
Handling Sessions and Cookies in PHP
PHP provides sessions and cookies for managing user data across different pages. Sessions
store data on the server, while cookies store data on the user's browser.
1. PHP Sessions
A session is a way to store user information (e.g., login data) across multiple pages. The
session data is stored on the server.
<?php
session_start(); // Start the session
$_SESSION["username"] = "JohnDoe";
$_SESSION["role"] = "Admin";
You can retrieve session variables on any page where session_start() is called.
<?php
session_start(); // Start the session
Output:
Welcome, JohnDoe!
Your role is: Admin
<?php
session_start(); // Start the session
2. PHP Cookies
A cookie is a small file stored on the user’s computer. PHP can set and read cookies to
remember user preferences.
<?php
$cookie_name = "user";
$cookie_value = "JohnDoe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 7), "/"); // 7-day expiry
<?php
if(isset($_COOKIE["user"])) {
echo "User: " . $_COOKIE["user"];
} else {
echo "No cookie found.";
}
?>
Output:
User: JohnDoe
This example demonstrates how to log in a user using sessions and cookies.
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<form method="post">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Login">
</form>
</body>
</html>
<?php
session_start();
if (!isset($_SESSION["user"])) {
header("Location: login.php");
exit();
}
if (isset($_COOKIE["user"])) {
echo "Remembered user: " . $_COOKIE["user"];
}
?>
<br><a href='logout.php'>Logout</a>
<?php
session_start();
session_unset();
session_destroy();
setcookie("user", "", time() - 3600, "/"); // Expire cookie
header("Location: login.php");
exit();
?>
PHP GET and POST Methods
PHP provides two primary ways to collect form data from users:
GET Method – Sends data via URL parameters.
POST Method – Sends data securely in the request body.
The $_GET superglobal is used to collect data sent via the URL.
<?php
if (isset($_GET["name"]) && isset($_GET["age"])) {
echo "Hello, " . htmlspecialchars($_GET["name"]) . "!<br>";
echo "You are " . (int)$_GET["age"] . " years old.";
} else {
echo "No data received.";
}
?>
Output:
Hello, John!
You are 25 years old.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST["name"]);
$age = (int)$_POST["age"];
<!DOCTYPE html>
<html>
<head><title>POST Example</title></head>
<body>
<form action="post_example.php" method="POST">
Name: <input type="text" name="name"><br>
Age: <input type="number" name="age"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
4. Security Considerations