"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Tuesday, June 12, 2018

Arrays in PHP

Why Use of an Array?

Suppose we want to store five names and print them accordingly. This can be easily done by the use of five different string variables. But if instead of five, the number rises to a hundred, then it would be really difficult for the user or developer to create so many different variables. Here array comes into play and helps us to store every element within a single variable and also allows easy access using an index or a key.
What is an array?
An array is a data structure that stores one or more similar type of values in a single value.The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key.  For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.
Arrays are complex variables that allow us to store more than one value or a group of values under a single variable name.
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of similar type in a single variable.

Advantage of PHP Array

  • Dynamic Size:    PHP arrays are dynamic, meaning you can add or remove elements without the need to declare a fixed size. This flexibility makes arrays suitable for handling varying amounts of data.
  • Versatility:    PHP arrays can store different data types within the same array. You can have a mix of strings, integers, floats, and even other arrays as elements within a single array.
  • Indexed and Associative Arrays:   PHP supports both indexed arrays (numeric keys) and associative arrays (string keys). This flexibility allows you to choose the most appropriate type based on your specific use case.
  • Efficient Data Retrieval:   PHP arrays provide fast and efficient data retrieval. You can quickly access an element using its key or index, making it suitable for scenarios where fast lookups are essential.
  • Built-in Array Functions:   PHP comes with a rich set of built-in array functions that make it easy to manipulate and process array data. Functions like count(), foreach(), array_map(), and array_filter() simplify common array operations.
  • Array Iteration:   PHP provides convenient ways to iterate through arrays, such as using foreach loops. This makes it easy to perform actions on each element of an array without dealing with explicit indexing.   
  • Passing Arrays to Functions:   PHP allows you to pass arrays to functions, making it convenient to work with collections of data. Functions can receive arrays as arguments, enabling modular and reusable code.   
  • Serialization and Unserialization:  PHP provides functions like serialize() and unserialize() that allow you to convert arrays into a string representation and vice versa. This is useful for storing arrays in databases or transferring them between different parts of an application.
  • Sorting and Searching:  PHP provides functions for sorting arrays (sort(), asort(), ksort(), etc.) and searching for specific values (in_array(), array_search(), etc.), making it easy to organize and retrieve data. 
  • JSON Representation: PHP arrays can be easily converted to JSON format using the json_encode() function. This is particularly useful for exchanging data between a PHP backend and a JavaScript frontend.
  • Memory Efficiency:     PHP arrays are implemented efficiently in terms of memory usage, making them suitable for handling large datasets without significant overhead.

Types of PHP Array
There are three different kind of arrays and each array value is accessed using an ID c which is called array index.
  1. Numeric array/Indexed array − An array with a numeric index. Values are stored and accessed in linear fashion.
  2. Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
  3. Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices

Create an Array in PHP

In PHP, there are different ways to create an array, and the syntax can vary depending on whether you're creating a numerically indexed array or an associatively indexed array.

1.Numeric array/Indexed array :

  1. In PHP,  the array() function is used to create a numerically indexed array:    Syntax:      array();
  2. An array with a numeric index is the Numeric array/Indexed array. Values are stored and accessed in linear fashion.
  3. These arrays can store numbers, strings and any object but their index will be represented by numbers.
  4. By default array index starts from zero.
  5. In an indexed or numeric array, the indexes are automatically assigned and start with 0 and the values can be any data type.
syntax for creating Indexed /Numeric array in php
There are two ways to create indexed arrays:
I)Using the array() function:
The index can be assigned automatically (index always starts at 0):
syntax:
<?php
$variable_name=array(n=> value,…);
?>
Example:
$cars = array("Volvo", "BMW", "Toyota");
$numericalArray = array(1, 2, 3, 4, 5);

II)Using the short array syntax [ ] (available in PHP 5.4 and later):
Syntax:
<?php
$variable_name[n]=value;
?>
HERE,
  • “$variable_name…” is the name of the variable
  • “[n]” is the access index number of the element
  • “value” is the value assigned to the array element.

Example:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
$numericalArray = [1, 2, 3, 4, 5];

Example:
Assigned automatically:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Output:
I like Volvo, BMW and Toyota.

Explanation:
  1. Here, an array named $cars is created and initialized with three elements: "Volvo", "BMW", and "Toyota".
  2. echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";   This line of code uses the echo statement to output a string. The string is constructed by concatenating various elements. Let's break it down to learn better:
  •  "I like ": A static string indicating the beginning of the sentence.
  • $cars[0]: Accesses the first element of the $cars array, which is "Volvo".
  • ", ": A static string used as a separator between the car names.
  • $cars[1]: Accesses the second element of the $cars array, which is "BMW".
  • " and ": A static string used before the last car name.
  • $cars[2]: Accesses the third element of the $cars array, which is "Toyota".
  • ".": A static string representing the end of the sentence.

Assigned manually:
<?php
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Traversing PHP Indexed Array

"Traversing PHP Indexed Array" refers to the process of iterating through each element of an indexed array in PHP. Traversing allows you to access and manipulate each element of the array sequentially. Indexed arrays in PHP are collections of values where each value is associated with a numeric index, starting from 0.

There are several ways to traverse (or loop through) an indexed array in PHP. Here are a few common methods:

Case 1: Using for Loop:

$numbers = array(1, 2, 3, 4, 5);

for ($i = 0; $i < count($numbers); $i++) {

echo $numbers[$i] . " ";

}

Output:

1 2 3 4 5

Explanation:

  • $numbers = array(1, 2, 3, 4, 5); : This line initializes an array named $numbers with the values 1, 2, 3, 4, and 5.
  • for ($i = 0; $i < count($numbers); $i++) { echo $numbers[$i] . " "; }
  • This for loop iterates through the array using an index ($i) starting from 0 and incrementing it until it reaches the count of elements in the array (count($numbers)). For each iteration, it prints the value of the array at the current index ($numbers[$i]) followed by a space.
  • The result of the loop is that each element of the array is printed to the screen, separated by spaces.
Case 2: Using foreach Loop:

$numbers = array(1, 2, 3, 4, 5);

foreach ($numbers as $number) {

echo $number . " ";

}

Output:

1 2 3 4 5

Explanation:

  • $numbers = array(1, 2, 3, 4, 5); This line initializes an array named $numbers with the values 1, 2, 3, 4, and 5.
  • foreach ($numbers as $number) { echo $number . " "; } This foreach loop iterates through each element of the array ($numbers) without the need for an explicit index. For each iteration, it assigns the current array element to the variable $number, and then it prints the value of $number followed by a space.
  • The result of the loop is that each element of the array is printed to the screen, separated by spaces.

Case 3: Using while Loop:

$numbers = array(1, 2, 3, 4, 5);

$count = count($numbers);

$i = 0;

while ($i < $count) {

echo $numbers[$i] . " ";

$i++;

}

Output:

1 2 3 4 5

Explanation:

  • $numbers = array(1, 2, 3, 4, 5); This line initializes an array named $numbers with the values 1, 2, 3, 4, and 5.
  • Counting Array Elements: $count = count($numbers); The count() function is used to determine the number of elements in the array, and the result is stored in the variable $count.
  • $i = 0; while ($i < $count) { echo $numbers[$i] . " "; $i++; } This while loop iterates through the array using an index ($i) starting from 0 and incrementing it until it reaches the count of elements in the array ($count). For each iteration, it prints the value of the array at the current index ($numbers[$i]) followed by a space.
  • The result of the loop is that each element of the array is printed to the screen, separated by spaces.

In each of these examples, the array $numbers is traversed, and each element is echoed or processed in some way. The for, foreach, and while loops are commonly used for traversing arrays, and the choice of loop depends on the specific requirements of your code.

Traversing an array is a fundamental operation in programming, and it allows you to perform actions on each element of the array, such as printing them, performing calculations, or updating their values.

Example2:

  1. <?php
  2. $size=array(“Big”,”Medium”,”Short”);
  3. foreach($size as $s)
  4. {
  5.    echo “Size is : $s<br/>”;
  6. } ?>
Count Length of PHP Indexed Array
PHP provides count() function which returns length of an array.
<?php
$size=array(“Big”,”Medium”,”Short”);
echo count($size);
?>

2)PHP Associative Array

  1. Associative array differ from numeric array in the sense that associative arrays use descriptive names for id keys.
  2. An associative array in PHP is an array where each element is associated with a specific key instead of being accessed by a numerical index. In other words, you use meaningful keys to represent values in the array. 
  3. In an associative array, the keys assigned to values can be arbitrary and user defined strings.
  4. In the Associative array, the array uses keys instead of index numbers.
  5. Associative array are also very useful when retrieving data from the database.
  6. The field names are used as id keys. 
  7. To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.
  8. Don't keep associative array inside double quote while printing otherwise it would not return any value.
syntax for creating associative array in php

There are two ways to create associative arrays:
Case I: The key assigned automatically (index always starts at 0):
Using the array() Function:
Syntax:
$associativeArray = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);
Example 1:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
Example 2:
$assocArray1 = array(
    'name' => 'John Doe',
    'age' => 25,
    'email' => 'john@example.com'
);
// Accessing values
echo $assocArray1['name'];  
echo $assocArray1['age'];   
echo $assocArray1['email']; 

Output:
John Doe
25
john@example.com
Case II: the key can be assigned manually:
Using the Short Array Syntax [] (PHP 5.4 and later):

Syntax:
$associativeArray = [
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
];
Example 1:
$mixedArray = [
    'name' => 'John Doe',
    'age' => 25,
    'isStudent' => false,
    'grades' => [90, 85, 92]
];
Example 2:
$assocArray2 = [
    'name' => 'Jane Doe',
    'age' => 30,
    'email' => 'jane@example.com'
];

// Accessing values
echo $assocArray2['name']; 
echo $assocArray2['age'];   
echo $assocArray2['email'];
Output:
John Doe
25
john@example.com

In both cases:
  1. Keys and values are separated by =>.
  2. Each key-value pair is separated by a comma.
  3. The entire associative array is enclosed in parentheses or square brackets.
  4. You can use various data types as keys and values, including strings, numbers, and even other arrays. Keys must be unique within an associative array.
Traversing PHP Associative Array(Looping in array)

Generally By the help of PHP for each loop, we can easily traverse the elements of PHP associative array. There are several ways to traverse (or loop through) an Associative array in PHP. Here are a few common methods:

Case 1: Using for Loop:

for traversing associative arrays in PHP, you can use a for loop in combination with functions like array_keys() or array_values().
Example 1:
$person = array(
    'name' => 'John Doe',
    'age' => 25,
    'email' => 'john@example.com'
);
// Using array_keys() to get an array of keys
$keys = array_keys($person);
// Using for loop to traverse the associative array based on keys
for ($i = 0; $i < count($keys); $i++) {
    $key = $keys[$i];
    $value = $person[$key];
    echo $key . ': ' . $value . '<br>';
}

Explanation:
  • $person = array(
              'name' => 'John Doe',
              'age' => 25,
              'email' => 'john@example.com'
               );
           This line initializes an associative array named $person with three key-value pairs: 'name', 'age', and 'email'.
  • Obtaining Keys with array_keys():   $keys = array_keys($person);
           The array_keys() function is used to obtain an array containing all the keys of the associative array. In this case, $keys will be an indexed array with values 'name', 'age', and 'email'.

  • Traversing the Array Using a for Loop:
                   for ($i = 0; $i < count($keys); $i++) {
                                $key = $keys[$i];
                                $value = $person[$key];
                                 echo $key . ': ' . $value . '<br>';
                           }
          The for loop is set up to iterate through the indexed array of keys ($keys).
          Inside the loop, $key is assigned the current key in each iteration.
          $value is then assigned the corresponding value in the associative array ($person) based on the current key.
           The loop body echoes the key, a colon, the value, and a line break (<br>).
  • Output:The result of the loop is that each key-value pair from the associative array is printed to the screen, separated by a colon and a line break.This code demonstrates an alternative way to traverse an associative array using a for loop, although it's generally less common than using foreach. The foreach loop is often preferred for its simplicity and readability when working with associative arrays.
Case 2: Using foreach Loop:

Using a foreach loop is a more common and concise way to traverse an associative array in PHP.
Example: $person = array( 'name' => 'John Doe', 'age' => 25, 'email' => 'john@example.com' ); // Using foreach loop to traverse the associative array foreach ($person as $key => $value) { echo $key . ': ' . $value . '<br>'; } Output: name: John Doe age: 25 email: john@example.com Explanation:
  1. An associative array named $person is created with three key-value pairs.
  2. The foreach loop is used to iterate through each key-value pair in the associative array.
  3. as $key => $value: For each iteration, the current key is assigned to the variable $key, and the corresponding value is assigned to the variable $value.
  4. Inside the loop, the echo statement prints the current key, a colon, the current value, and a line break (<br>).
  5. The result of the loop is that each key-value pair from the associative array is printed to the screen, separated by a colon and a line break.
Example 2:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";
}
?>
Example 2:
<?php
/* First method to create an associate array*/
$salaries=array(“mohammad”=>20000, “rahul”=>12000, “mahima”=>30000);
echo “Salary of is”. $salaries[‘mohammed’]. “<br/>”;
echo “Salary of is”. $salaries[‘rahul]. “<br/>”;
echo “Salary of is”. $salaries[‘mahima]. “<br/>”;
/* Second method to create an associate array*/
$salaries=array(“mohammad”=>20000, “rahul”=>12000, “mahima”=>30000);
$salaries[‘mohammed’]=”high”;
$salaries[‘rahul]=”medium”;
$salaries[‘mahima]=”low”;

echo “Salary of is”. $salaries[‘mohammed’]. “<br/>”;
echo “Salary of is”. $salaries[‘rahul]. “<br/>”;
echo “Salary of is”. $salaries[‘mahima]. “<br/>”;
?>

Case 1: Using while Loop:

While using a while loop to traverse an associative array might be less common than using foreach, you can achieve it by combining each() and list() functions.
Example:
$person = array(
    'name' => 'John Doe',
    'age' => 25,
    'email' => 'john@example.com'
);

// Get the first key-value pair from the associative array
list($key, $value) = each($person);

// Using while loop to traverse the associative array
while ($key !== null) {
    echo $key . ': ' . $value . '<br>';
    
    // Get the next key-value pair
    list($key, $value) = each($person);
}

Output:
name: John Doe
age: 25
email: john@example.com

Explanation:

  • An associative array named $person is created with three key-value pairs.
  • Get the First Key-Value Pair:    list($key, $value) = each($person);                                             The each() function is used to get the first key-value pair from the associative array.                 The list() function is then used to assign the key to $key and the value to $value.
  • While Loop for Traversal:
                       while ($key !== null) {
                                        echo $key . ': ' . $value . '<br>';

                                    // Get the next key-value pair
                                       list($key, $value) = each($person);
                                }
  • The while loop is used to iterate through the associative array until the internal array pointer reaches the end.
  • The loop condition checks if the current key ($key) is not equal to null.
  • Inside the loop, the key-value pair is echoed, and then each() is used again to get the next key-value pair.
  • Output:        The result of the loop is that each key-value pair from the associative array is printed to the screen, separated by a colon and a line break.



3.  Multidimensional Arrays


  1. In PHP, a multidimensional array is an array that contains one or more arrays as its elements. These inner arrays can, in turn, contain other arrays, creating a nested or hierarchical structure. Multidimensional arrays are useful for representing and working with more complex data structures. 
  2. PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an array.
  3. A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.
  4. The multidimensional array is an array in which each element can also be an array and each element in the sub-array can be an array or further contain array within itself and so on.
  5. PHP multidimensional array can be represented in the form of matrix which is represented by row * column.
  6. The advantage of multidimensional arrays is that they allow us to group related data together.

PHP - Two-dimensional Arrays

A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).
There are two ways to create multidimensional arrays(here  two-dimensional array):

Case I:Using the array() Function:
Syntax:
$students = array(
    array('John', 20, 'A'),
    array('Jane', 22, 'B'),
    array('Doe', 21, 'C')
);
Explanation:
$students is a two-dimensional array.
Each element of $students is itself an array representing a student's information (name, age, and grade).
The inner arrays have three elements each.

Case II: the key can be assigned manually:
Using the Short Array Syntax [ ] (PHP 5.4 and later):

Syntax:
$students = [
    ['John', 20, 'A'],
    ['Jane', 22, 'B'],
    ['Doe', 21, 'C']
];
  • The $students array is initialized using the short array syntax ([]). 
  • It is a two-dimensional array with three inner arrays, each representing a student's information.
  • Each inner array represents a student.
                The first element is the student's name (string).
                The second element is the student's age (integer).
                The third element is the student's grade (string).

Accessing Elements in the Multidimensional Array:

You can access elements in the multidimensional array using multiple sets of square brackets. 
For example, $students[0][0] accesses the name of the first student.

Traversing the Multidimensional Array with foreach:

foreach ($students as $student) {
    foreach ($student as $value) {
        echo $value . ' ';
    }
    echo '<br>';
}
This code uses nested foreach loops to traverse through the entire multidimensional array. 
The outer loop iterates over each student, and the inner loop iterates over each value (name, age, grade) within the student's information. 
The values are echoed with a space between them, and a line break (<br>) is added after each student.

Output:
John 20 A 
Jane 22 B 
Doe 21 C 
The output of the nested foreach loop displays each student's information on a new line, with values separated by spaces.

Multidimensional arrays are useful for organizing structured data, and they are commonly used in scenarios where data has a hierarchical or tabular structure, such as representing tables in a database or storing matrices in mathematical computations.

Example:
<?php
// Multidimensional array representing student information
$students = [
    ['John', 20, 'A'],
    ['Jane', 22, 'B'],
    ['Doe', 21, 'C']
];
// Displaying student information using a foreach loop
echo '<h2>Student Information</h2>';
echo '<ul>';

foreach ($students as $student) {
    echo '<li>';
    foreach ($student as $value) {
        echo $value . ' ';
    }
    echo '</li>';
}

echo '</ul>';
?>
Output:
Student Information

John 20 A 
Jane 22 B 
Doe 21 C 

Explanation:
  • Array Initialization:
The $students array is initialized as a multidimensional array using the short array syntax ([]).
Each inner array represents a student's information, consisting of the name (string), age (integer), and grade (string).
  • Display Setup:
The program begins by echoing an HTML heading (<h2>) and an unordered list (<ul>) to structure the display of student information.
  • Foreach Loop for Display:
                                The outer foreach loop iterates through each student in the $students array.
                                Inside the outer loop, a list item (<li>) is echoed for each student.
                                The inner foreach loop iterates through each value within the student's information array, echoing the values with a space between them.
  • Closing Tags:
The program concludes by echoing the closing tag for the unordered list (</ul>).

Example 2:
 $cars = array
  (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
  );
How to get the access from the two-dimensional array
There are 2 ways to get access :
1)simple way
Example:
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
2)using for loop:
<?php
for ($row = 0; $row < 4; $row++) {
  echo "<p><b>Row number $row</b></p>";
  echo "<ul>";
  for ($col = 0; $col < 3; $col++) {
    echo "<li>".$cars[$row][$col]."</li>";
  }
  echo "</ul>";
}
?>
We can also put a for loop inside another for loop to get the elements of the $cars array (we still have to point to the two indices):

Example:
Here we create a two dimensional array to store marks of three students in three subjects –
<?php
$marks=array(“mohammad”=>array(“physics”=>65, “maths”=>75, “chemistry”=>35),
“rahul”=>array(“physics”=>65, “maths”=>75, “chemistry”=>35),
“lopa”=>array(“physics”=>95, “maths”=>95, “chemistry”=>85)
);
/*Accessing multi-dimensional array values */
echo “Marks for mohammad in physics:”;
echo $marks[‘mohammad’][‘physics’].”<br/>;
echo “Marks for Rahul in math:”;
echo $marks[‘rahul][‘maths].”<br/>;
echo “Marks for Lopa in chemistry:”;
echo $marks[‘lopa][‘chemistry].”<br/>;
?>



No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template