Arrays in PHP

王林
Release: 2024-08-29 12:42:53
Original
645 people have browsed it

The following article, Arrays in PHP, provides an outline for creating arrays in PHP. An array is a collection of similar data types. An array stores multiple values in a single variable. Why is there a need for an array when storing a value can also be done by a variable? The answer is because to store values of limited data like the count of numbers 5 is possible, but when the count increases to, say, 100 or 200, we need to store 100 values in 100 variables which is a bit difficult; thus, we store it in an array. This is why arrays are used.

ADVERTISEMENT Popular Course in this category PHP DEVELOPER - Specialization | 8 Course Series | 3 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

How to Create Arrays in PHP?

Syntax:

variablename = array();
Copy after login

OR

variablename[i] = value;
Copy after login

Where the variable name is the name of the variable i is the key, or the index value is the element value.

Example to Create an Array

$colors = array("Red","Green","Blue");
Copy after login

To calculate the length of the array, we use the count keyword.

$length = count($colors); // output is 3
Copy after login

Each value in the array is termed as an element of the array. The array index begins with 0. And the index of the last element in an array is the total length of the array minus 1.

In the given example above, the index of Red is 0, Green is 1, and Blue is 2. Thus, accessing the array with the help of the index or a key becomes easier. To get the value at each index of an array, we loop through the given array. To loop the array, we use a foreach loop or for a loop.

How does the Array work in PHP?

Loops like for each and for are used to loop through the array. Each array has starting indexes from 0 and so on:

Types of Arrays in PHP

There are three types of array in PHP; let us learn each type of array in detail:

  1. Numeric or Indexed Array
  2. Associative Array
  3. Multidimensional Array
1. Numeric Array

In this array type, where an index is always a number, it cannot be a string. Instead, it can store any number of elements and any type of element.

Syntax:

variable name = array("value1","value2","value3","value4")
Copy after login

Code:

<?php
//Example to demonstrate numeric array
$input = array("Apple", "Orange", "Banana", "Kiwi");
//Here, to get these values we will write like
echo $input[0] . "\n"; // will give Apple
echo $input[1] . "\n"; // will give Orange
echo $input[2] . "\n"; // will give Banana
echo $input[3] . "\n"; // will give Kiwi
// To get the length of array we will use count
echo "The count of the array is " . count($input); // will give 4
echo "\n";
//To print the array we can use
print_r($input);
?>
Copy after login

Output:

Arrays in PHP

OR

The other way to declare the numeric array is the following program. In this program, we will also see to modify and print value.

Code:

<?php
//Example to demonstrate numeric array in another way
$input[0] = "Apple";
$input[1] = "Orange";
$input[2] = "Banana";
$input[3] = "Kiwi";
// To get Kiwi we will write like
echo $input[3]."<br>"; // will give Kiwi
//To modify Orange value
$input[1] = "Mango";
// Now echo $input[1] will give Mango
echo $input[1]."<br>"; // Mango
//To print the array we can use
print_r($input);
?>
Copy after login

Output:

Arrays in PHP

Now we will learn how to use the for loop to traverse through an array

Code:

<?php
//Example to demonstrate for loop on a numeric array
//declaring the array
$input = array("Apple", "Orange", "Banana", "Kiwi", "Mango");
//the for loop to traverse through the input array
for($i=0;$i<count($input); $i++) {
echo $input[$i];
echo "<br>";
}
?>
Copy after login

Output:

Arrays in PHP

2. Associative Array

This array is in the form of a key-value pair, where the key is the index of the array, and the value is the element of the array.

Syntax:

$input = array("key1"=>"value1",
"key2"=>"value2",
"key3"=>"value3",
"key4"=>"value4");
Copy after login

OR

The other way to declare an associative array without an array keyword

$input[$key1] = $value1;
$input[$key2] = $value2;
$input[$key3] = $value3;
$input[$key4] = $value4;
Copy after login

Code:

<?php
//Example to demonstrate associative array
//declaring an array
$input = array(
"Jan"=>31,
"Feb"=>28,
"Mar"=>31,
"Apr"=>30);
// the for loop to traverse through the input array
foreach($input as $in) {
echo $in."<br>";}
?>
Copy after login

Output:

Arrays in PHP

3. Multidimensional Array

This array is an array of the array where the value of the array contains an array.

Syntax:

$input =array(
array('value1', 'value2', 'value3'),
array('value4', 'value5', 'value6'),
array('value7', 'value8', 'value9'));,
Copy after login

Code:

<?php
//Example to demonstrate multidimensional array
// declaring a multidimensional array
$input = array ("colors"=>array ("Red", "Green", "Blue"),
"fruits"=>array ("Apple", "Orange", "Grapes"),
"cars"=>array ("Skoda", "BMW", "Mercedes")
);
//the foreach loop to traverse through the input array
foreach($input as $key=>$value) {
echo $key .'--'. "<br>";
foreach($value as $k=>$v)
{echo $v ." ";}
echo "<br>";
}
?>
Copy after login

Output:

Arrays in PHP

OR

Multidimensional Array in an Associative Array

Code:

<?php
//Example to demonstrate multidimensional array
// declaring a multidimensional array
$input = array(
"The_Alchemist" => array (
"author" => "Paulo Coelho",
"type" => "Fiction",
"published_year" => 1988),
"Managing_Oneself" => array(
"author" => "Peter Drucker",
"type" => "Non-fiction",
"published_year" => 1999
),"Measuring_the_World" => array(
"author" => "Daniel Kehlmann",
"type" => "Fiction",
"published_year" => 2005
));
//the foreach loop to traverse through the input array
//foreach to loop the outer array
foreach($input as $book) {
echo "<br>";
// foreach to loop the inner array
foreach($book as $key=>$value)
{
echo $key." ". $value. "<br>";}
}?>
Copy after login

Output:

Arrays in PHP

Methods of Array in PHP

Below are the methods of Array in PHP:

1. Count() method

This method is used to count the number of elements in an array.

Syntax:

Count(array, mode)
Copy after login

where the count is required, the mode is optional.

Code:

<?php
//Example to demonstrate use of in_array method
//declaring associative array
$input=array('English','Hindi','Marathi');
//counting the number of elements in the given array
echo count($input);
?>
Copy after login

Output:

Arrays in PHP

2. Array_walk() method

This method takes two parameters as input; the first parameter is the input array, and the second parameter is the name of the function declared. This method is used to loop through each element in the array.

Syntax :

array_walk(array, function_name, parameter...)
Copy after login

where array is required function_name is required

parameter is optional

Code:

<?php
//Example to demonstrate use of array_walk method
//creating a function to print the key and values of the given array
function fun($val, $k) {
echo $k. " --" .$val ."\n";
}
// declaring associative array
$input=array("e"=>'English', "h"=>'Hindi', "m"=>'Marathi');
//passing this array as a first parameter to the function
// array_walk,
//second paramter as the name of the function being called
array_walk($input,"fun");
?>
Copy after login

Output:

Arrays in PHP

3. In_array() method

This method performs a search on the array, whether the given array contains a particular value or not. If found or not found, it will execute respective if, else block

Syntax:

in_array(search_value, array_name)
Copy after login

Where both the parameters are required

Code:

<?php
//Example to demonstrate use of in_array method
// declaring associative array
$input=array('English','Hindi','Marathi', "Maths", "Social Science");
// using in_array to find Maths in given array
if(in_array("Maths", $input)) {
echo "Found Maths in the given array";
}
else
{
echo "Did not find Maths in the given array";
}
?>
Copy after login

Output:

Arrays in PHP

4. Array_pop() method

This method removes the last element from the given array.

Syntax

array_pop(array_name)
Copy after login

Code:

<?php
//Example to demonstrate use of array_pop method
// declaring array
$input=array('English','Hindi','Marathi');
// before using array_pop on the given array
print_r($input);
// after using array_pop method on the given array
array_pop($input);
echo "\n ";
print_r($input);
?>
Copy after login

Output:

Arrays in PHP

5. Array_push() method

This method adds given elements at the end of the array.

Syntax:

array_push(array_name, value1, value2, ...)
Copy after login

Code:

<?php
//Example to demonstrate use of array_push method
// declaring array
$input=array('English','Hindi','Marathi');
// before using array_push on the given array
print_r($input);
// after using array_push method on the given array
array_push($input, "Economics", "Maths", "Social Science");
echo "\n";
//printing the array
print_r($input);
?>
Copy after login

Output:

Arrays in PHP

6. Array_shift() method

This method removes and returns the first element of the array.

Syntax: 

array_shift(array_name)
Copy after login

Code:

<?php
//Example to demonstrate use of array_push method
// declaring array
$input=array('English','Hindi','Marathi');
// before using array_shift on the given array
print_r($input);
echo "\n";
// after using array_shift method on the given array
echo array_shift($input);
?>
Copy after login

Output:

Arrays in PHP

7. Array_unshift() method

This method inserts given elements into the beginning of the array.

Syntax:

array_unshift(array_name, value1, value2,…)
Copy after login

Code:

<?php
//Example to demonstrate use of array_push method
// declaring array
$input=array('English','Hindi','Marathi');
// before using array_unshift on the given arrayprint_r($input);
echo "\n";
// after using array_unshift method on the given array
array_unshift($input, "Economics");
print_r($input);
?>
Copy after login

Output:

Arrays in PHP

8. Array_reverse() method

This method is used to reverse the elements of the array.

Syntax:

array_reverse(array_name, preserve)
Copy after login

where array_name is required,

preserve is optional

Code:

<?php
//Example to demonstrate use of in_array method
// declaring associative array
$input=array("e"=>'English',"h"=>'Hindi',"m"=>'Marathi');
// array before reversing the elements
print_r($input);
echo "\n";
// printing the reverse
// array after reversing the elements
print_r(array_reverse($input));
?>
Copy after login

Output:

Arrays in PHP

Conclusion

This article covers all levels of concepts, simple and complex, of the topic arrays in PHP. I hope you found this article interesting and informative for the learning purpose.

The above is the detailed content of Arrays in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template