Unit CHAP-2 ARREY
Unit CHAP-2 ARREY
CHAPTER-2
Introduction to PHP Arrays
In PHP, an array is a variable that can store multiple values under a single name. Arrays help manage
and manipulate large amounts of data efficiently. PHP arrays are flexible and can store different data
types, including integers, strings, objects, and even other arrays.
PHP arrays are widely used in web development for tasks such as storing form data, handling
database results, and processing JSON data. They are dynamically resizable, allowing elements to be
added or removed without predefined limits.
An array in PHP is a collection of elements, each identified by an index (numeric or string-based key).
It provides a structured way to store and access multiple values within a single variable.
You can create an array using the array() function or the short [] syntax:
/ Indexed array
// Associative array
$person = array("name" => "John", "age" => 30, "city" => "New York");
$student = ["id" => 101, "grade" => "A"];
// Multidimensional array
$students = array(
);
PHP arrays can store a mix of different data types. You can store integers, strings, objects, or even
arrays in the same array.
2. Associative Arrays
PHP supports associative arrays, where each value is associated with a custom key (a string or
number). This is useful for creating key-value pairs.
$person = [
];
3. Dynamic Sizing
PHP arrays do not require a fixed size declaration. You can add or remove elements dynamically.
4. Flexible Indexing
5. Multidimensional Arrays
$students = [
];
6. Loose Typing
PHP does not enforce strict data types for array elements, so an array can contain a mix of different
data types.
Arrays in PHP are an essential data structure used to store multiple values in a single variable. They
allow for efficient storage and manipulation of data, making them crucial for handling large amounts
of information.
PHP arrays are categorized into three primary types based on their indexing and structure:
These arrays are the simplest form of PHP arrays. They use numeric keys to store and access
elements. PHP assigns numeric indices starting from 0.
1. Ordered Collection
o Elements are stored in a specific order and accessed based on their index.
2. Sequential Access
3. Zero-Based Indexing
o The first element has an index of 0, the second element has an index of 1, and so on.
4. Array Functions
o Useful functions include:
5. Memory Efficiency
7. Array Iteration
Syntax:
Example:
Syntax:
Example:
Elements are accessed using their numeric index. The first element has an index of 0.
Syntax:
$arrayName[index];
Explanation:
$colors = [];
Explanation:
Explanation:
2. The condition $i < count($fruits) ensures the loop runs until all elements are printed.
Output:
Apple
Banana
Orange
Mango
Numerically indexed arrays in PHP provide an efficient and straightforward way to manage ordered
collections of data. They support dynamic addition, modification, and iteration using built-in
functions and loops.
Key points:
Introduction
An associative array in PHP is a type of array where each element is assigned a unique key, which
can be a string or an integer. Unlike numerically indexed arrays, which rely on numbers to access
elements, associative arrays use meaningful keys, making data retrieval more intuitive.
• Making data more readable and meaningful (e.g., using name instead of [0]).
• Example:
$studentGrades = array(
"Charlie" => 78
);
2. Named Access
• Example:
• Example:
$userInfo = array(
"Age" => 30
);
• Example:
Output:
Alice: 85
Bob: 90
Charlie: 78
$person = array(
);
$person = [
];
$employee = [
];
if (array_key_exists("position", $employee)) {
} else {
$employee["salary"] = 65000;
$employee["department"] = "IT";
print_r($employee);
Output:
Array ( [name] => Jane Doe [position] => Software Engineer [salary] => 65000 [department] => IT )
$studentGrades = [
"Charlie" => 78
];
foreach ($studentGrades as $name => $grade) {
PHP supports nested associative arrays, useful for storing structured data.
$books = [
"book1" => [
],
"book2" => [
],
"book3" => [
];
Output:
Price: 300
Price: 350
Price: 250
The foreach loop is a control structure in PHP that simplifies iterating over arrays and objects. Unlike
the for or while loops, foreach is specifically designed for collections, eliminating the need for
manual index management.
Syntax
<?php
?>
Output
Explanation
• $number holds the current element's value in each iteration and is printed.
$ages = ["Swati" => 23, "Srikanth" => 40, "Lakshmi" => 35];
?>
Output
Explanation
• The associative array $ages stores names as keys and ages as values.
• $name holds the key (person's name), and $age holds the corresponding value (age).
o Incorrect:
o Correct:
Multidimensional arrays are used to store and organize data in a tabular format, where data is
arranged in rows and columns. They are particularly useful in:
Syntax
$arrayName = array(
);
// OR using shorthand
$arrayName = [
];
• Each inner array can contain different elements, including numbers, strings, or even other
arrays.
<?php
$students = array(
);
// Accessing elements
echo "<br>";
?>
Explanation
• Each element is itself an associative array with "name" and "age" keys.
• We access the elements using their index and key, like $students[0]["name"].
<?php
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
?>
Explanation
<?php
$users = array(
);
?>
Explanation
• Each key "SK" and "RK" stores another associative array with "name" and "age".
<?php
$threeDArray = array(
array(
array("a", "b"),
array("c", "d")
),
array(
array("e", "f"),
array("g", "h")
);
?>
Explanation
• This is a 3D array with three levels.
• $threeDArray[0][1][0] selects the first element ("c") from the second row of the first 2D
array.
<?php
$departments = array(
);
?>
Explanation
<?php
$students = array(
);
?>
Output
Key Takeaways
• You can create them using either numeric (indexed) arrays or associative arrays.
PHP provides a powerful set of array functions that help in performing various operations such as
sorting, counting, merging, extracting, and more. These functions simplify array manipulation and
improve code efficiency.
Function: is_array()
Example
<?php
?>
Explanation
Function: count()
<?php
?>
Explanation
3. Sorting an Array
Function: sort()
Example
<?php
sort($arr);
print_r($arr);
?>
Output
Explanation
4. Randomizing an Array
Function: shuffle()
Example
<?php
shuffle($arr);
print_r($arr);
?>
Output (randomized)
Explanation
Function: explode()
Example
<?php
$str = "one,two,three";
print_r(explode(",", $str));
?>
Output
Array ( [0] => one [1] => two [2] => three )
Explanation
• explode(",", $str) breaks the string into an array using , as the delimiter.
Function: extract()
Example
<?php
extract($arr);
?>
Explanation
Example
<?php
$color = "blue";
$size = "medium";
print_r(compact("color", "size"));
?>
Output
Explanation
• compact("color", "size") creates an array with keys color and size and assigns their values.
Example
?>
Explanation
Function: array_push()
Example
<?php
$arr = [1, 2];
array_push($arr, 3, 40);
print_r($arr);
?>
Output
Explanation
Function: array_pop()
Example
<?php
$last = array_pop($arr);
print_r($arr);
?>
Output
Explanation
Function: array_merge()
Example
<?php
print_r($merged);
?>
Output
Explanation
Function: array_keys()
Example
<?php
$keys = array_keys($arr);
print_r($keys);
?>
Output
Explanation
Function: array_values()
Example
<?php
$arr = ["a" => 10, "b" => 20, "c" => 30];
$values = array_values($arr);
print_r($values);
?>
Output
Explanation
Conclusion
PHP provides a variety of array functions that help in efficient array manipulation. Some of the most
commonly used functions include:
PHP provides several built-in functions to manipulate arrays efficiently. These functions help in
sorting, merging, counting, searching, and modifying arrays.
Function Description
<?php
sort($fruits);
echo "<ul>";
echo "<li>$fruit</li>";
echo "</ul>";
?>
Output:
• Apple
• Banana
• Cherry
• Grape
• Orange
Explanation:
3. The sorted elements are displayed in an unordered list using a foreach loop.
PHP provides include() and require() functions to reuse code by importing external PHP files.
• If the file is missing, it issues a warning but allows the script to continue.
Syntax:
include 'filename.php';
// header.php
<header>
<h1>Welcome to My Website</h1>
</header>
// footer.php
<footer>
</footer>
// main.php
<?php
include 'header.php';
echo "<section>";
echo "</section>";
include 'footer.php';
?>
Explanation:
• Works like include(), but if the file is missing, it causes a fatal error and stops script
execution.
Syntax:
require 'filename.php';
<?php
?>
PHP is a loosely typed language, meaning variables can change their data type automatically based
on usage.
<?php
?>
Explanation:
<?php
?>
Explanation:
• Later, it’s assigned a string, and PHP allows this change dynamically.
Syntax:
<?php
$floatValue = 10.5;
?>
Explanation:
<!DOCTYPE html>
<html>
<head>
<title>Array Sorting</title>
</head>
<body>
<?php
sort($fruits);
echo "<ul>";
echo "<li>$fruit</li>";
echo "</ul>";
?>
</body>
</html>
Output:
• Apple
• Banana
• Cherry
• Grape
• Orange
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$sum = array_sum($numbers);
?>
</body>
</html>
Output:
Explanation: