Web Development
HTML Course
CSS Course
JavaScript Course
PHP Course
Python Course
SQL Course
SEO Course

Indexed Arrays in PHP

An indexed array is an array where each element has a numeric index, starting from 0. This type of array is useful when the order of elements matters and you want to access them quickly by position.

Creating an Indexed Array

<?php
$fruits = ["apples", "pears", "bananas"];
?>

Accessing elements

<?php
echo $fruits[0]; // displays "apples"
echo $fruits[2]; // displays "bananas"
?>

Adding a new element

<?php
$fruits[] = "oranges"; // adds to the end of the array
?>

Looping through an Indexed Array

<?php
foreach ($fruits as $fruit) {
    echo "I like to eat $fruit <br>";
}
?>

Indexed arrays are the foundation for many operations in PHP and serve as a starting point for associative or multidimensional arrays.

Associative Arrays in PHP

An associative array is an array where elements are stored using custom keys instead of numeric indexes. This is useful when you want to identify values with a descriptive name rather than their position.

Creating an Associative Array

<?php
$person = [
    "name" => "John",
    "age" => 30,
    "city" => "Bucharest"
];

var_dump($person);
?>

Accessing values

<?php
echo "The name is: " . $persoana["nume"] . "<br>";
echo "The age is: " . $persoana["varsta"] . "<br>";
echo "The city is: " . $persoana["oras"] . "<br>";
?>

Adding and modifying elements

<?php
// Add a new key
$persoana["profesie"] = "Programmer";

// Modify an existing value
$persoana["varsta"] = 31;

var_dump($persoana);
?>

Iterating over an associative array

<?php
foreach ($persoana as $cheie => $valoare) {
    echo "$cheie : $valoare <br>";
}
?>

Associative arrays are very useful for storing structured data, such as user profiles, application settings, or any kind of data where the field names matter more than the position.

Practical example: displaying an HTML table from arrays

<?php
$utilizatori = [
    [
        "nume" => "John Smith",
        "varsta" => 28,
        "oras" => "Bucharest"
    ],
    [
        "nume" => "Mary Johnson",
        "varsta" => 25,
        "oras" => "Cluj-Napoca"
    ],
    [
        "nume" => "Andrew Williams",
        "varsta" => 32,
        "oras" => "Timisoara"
    ]
];
?>

<?php
echo '<table border="1" cellpadding="5">';
echo '<tr><th>Name</th><th>Age</th><th>City</th></tr>';

foreach ($utilizatori as $user) {
    echo '<tr>';
    echo '<td>' . htmlspecialchars($user["nume"]) . '</td>';
    echo '<td>' . htmlspecialchars($user["varsta"]) . '</td>';
    echo '<td>' . htmlspecialchars($user["oras"]) . '</td>';
    echo '</tr>';
}

echo '</table>';
?>

In this example:

๐Ÿ”ง PHP Example: displaying an HTML table from arrays
<?php
// Define the multidimensional array
$users = [
    [
        "name" => "John Smith",
        "age" => 28,
        "city" => "New York"
    ],
    [
        "name" => "Mary Johnson",
        "age" => 25,
        "city" => "Los Angeles"
    ],
    [
        "name" => "Andrew Williams",
        "age" => 32,
        "city" => "Chicago"
    ]
];

// Display in an HTML table
echo '<table border="1" cellpadding="5">';
echo '<tr><th>Name</th><th>Age</th><th>City</th></tr>';

foreach ($users as $user) {
    echo '<tr>';
    echo '<td>' . htmlspecialchars($user["name"]) . '</td>';
    echo '<td>' . htmlspecialchars($user["age"]) . '</td>';
    echo '<td>' . htmlspecialchars($user["city"]) . '</td>';
    echo '</tr>';
}

echo '</table>';
?>

Thus, we can combine the numeric indexing of the main array with the descriptive keys from the inner arrays, making the code clear and easy to maintain.

Multidimensional Arrays in PHP

A multidimensional array is an array that contains one or more arrays as elements. It is useful when we want to store and organize complex data, for example tables with users, products, or sets of values.

Practical example: table with students' grades

We define a multidimensional array where each student has several grades:

<?php
$students = [
    "John" => ["Math" => 9, "Romanian" => 10, "ComputerScience" => 10],
    "Mary" => ["Math" => 8, "Romanian" => 9, "ComputerScience" => 9],
    "Andrew" => ["Math" => 10, "Romanian" => 8, "ComputerScience" => 10]
];

// Display HTML table
echo '<table border="1" cellpadding="5">';
echo '<tr><th>Name</th><th>Math</th><th>Romanian</th><th>ComputerScience</th></tr>';

foreach ($students as $name => $grades) {
    echo '<tr>';
    echo '<td>' . htmlspecialchars($name) . '</td>';
    echo '<td>' . htmlspecialchars($grades["Math"]) . '</td>';
    echo '<td>' . htmlspecialchars($grades["Romanian"]) . '</td>';
    echo '<td>' . htmlspecialchars($grades["ComputerScience"]) . '</td>';
    echo '</tr>';
}

echo '</table>';
?>

This example shows how we can store multiple values for each element of the array and how we can iterate through all values for display.

๐Ÿ”ง PHP Example: table with students' grades
<?php
$students = [
    "John" => ["Math" => 9, "Romanian" => 10, "Computer Science" => 10],
    "Mary" => ["Math" => 8, "Romanian" => 9, "Computer Science" => 9],
    "Andrew" => ["Math" => 10, "Romanian" => 8, "Computer Science" => 10]
];

// Display HTML table
echo '<table border="1" cellpadding="5">';
echo '<tr><th>Name</th><th>Math</th><th>Romanian</th><th>Computer Science</th></tr>';

foreach ($students as $name => $grades) {
    echo '<tr>';
    echo '<td>' . htmlspecialchars($name) . '</td>';
    echo '<td>' . htmlspecialchars($grades["Math"]) . '</td>';
    echo '<td>' . htmlspecialchars($grades["Romanian"]) . '</td>';
    echo '<td>' . htmlspecialchars($grades["Computer Science"]) . '</td>';
    echo '</tr>';
}

echo '</table>';
?>

Useful functions for arrays in PHP

PHP provides several built-in functions to manipulate arrays quickly and efficiently. The most used ones are: array_map, array_filter and array_merge.

1. array_map - apply a function to each element

Example: increase each grade by 1 point:

<?php
$grades = [8, 9, 10, 7];

$raised_grades = array_map(function($grade) {
    return $grade + 1;
}, $grades);

print_r($raised_grades); // Output: [9, 10, 11, 8]
?>

2. array_filter - filter array elements

Example: keep only grades greater than or equal to 9:

<?php
$grades = [8, 9, 10, 7];

$good_grades = array_filter($grades, function($grade) {
    return $grade >= 9;
});

print_r($good_grades); // Output: [9, 10]
?>

3. array_merge - combine two or more arrays

Example: merge two student groups:

<?php
$group1 = ["John", "Mary"];
$group2 = ["Andrew", "Helen"];

$whole_class = array_merge($group1, $group2);

print_r($whole_class); // Output: ["John", "Mary", "Andrew", "Helen"]
?>

These functions make array manipulation much faster and the code cleaner. They can also be used together with multidimensional arrays for processing complex data.

JSON Conversion in PHP

JSON (JavaScript Object Notation) is a very common format for data exchange between server and client. PHP provides two main functions: json_encode (convert array or object to JSON) and json_decode (convert JSON to PHP array or object).

1. json_encode - convert array to JSON

<?php
$users = [
    ["name" => "John", "age" => 25],
    ["name" => "Mary", "age" => 22]
];

$json = json_encode($users);

echo $json;
// Output: [{"name":"John","age":25},{"name":"Mary","age":22}]
?>

2. json_decode - convert JSON into array or object

Example: convert JSON into an associative array:

<?php
$json = '[{"name":"John","age":25},{"name":"Mary","age":22}]';

$users = json_decode($json, true); // true => associative array

print_r($users);
/* Output:
Array
(
    [0] => Array
        (
            [name] => John
            [age] => 25
        )

    [1] => Array
        (
            [name] => Mary
            [age] => 22
        )
)
*/
?>

Why do we use JSON in PHP?

Practical Example - JSON in PHP

Suppose we have an application where we want to send user data to a JavaScript frontend or save it into a JSON file. We'll see how to convert a PHP array to JSON and how to read it back.

1. Creating and converting an array into JSON

<?php
$users = [
    ["name" => "John", "email" => "john@example.com", "age" => 25],
    ["name" => "Mary", "email" => "mary@example.com", "age" => 22],
    ["name" => "Alex", "email" => "alex@example.com", "age" => 30]
];

// Convert array to JSON
$json = json_encode($users);

echo "<h4>Generated JSON:</h4>";
echo "<pre>$json</pre>";
?>

2. Reading JSON and using it in PHP

<?php
// Suppose $json comes from a file or an API
$json = '[{"name":"John","email":"john@example.com","age":25},{"name":"Mary","email":"mary@example.com","age":22},{"name":"Alex","email":"alex@example.com","age":30}]';

// Convert JSON into an associative array
$users = json_decode($json, true);

echo "<h4>User list:</h4>";
echo "<ul>";
foreach ($users as $user) {
    echo "<li>" . $user['name'] . " (" . $user['email'] . ") - " . $user['age'] . " years old</li>";
}
echo "</ul>";
?>
๐Ÿ”ง PHP Example: Reading JSON and using it in PHP
<?php
// Suppose $json comes from a file or an API
$json = '[{"name":"John","email":"ion@example.com","age":25},{"name":"Mary","email":"maria@example.com","age":22},{"name":"Alex","email":"alex@example.com","age":30}]';

// Convert JSON to an associative array
$users = json_decode($json, true);

echo "<h4>User List:</h4>";
echo "<ul>";
foreach ($users as $user) {
    echo "<li>" . $user['name'] . " (" . $user['email'] . ") - " . $user['age'] . " years old</li>";
}
echo "</ul>";
?>

3. Concrete examples of using JSON


๐Ÿง  Quiz - Arrays & Data Structures in PHP

Top