Arrays in PHP
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 TestsStart Your Free Software Development Course
Web development, programming languages, Software testing & others
How to Create Arrays in PHP?
Syntax:
variablename = array();
OR
variablename[i] = value;
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");
To calculate the length of the array, we use the count keyword.
$length = count($colors); // output is 3
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:
- Numeric or Indexed Array
- Associative Array
- 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")
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); ?>
Output:
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); ?>
Output:
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>"; } ?>
Output:
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");
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;
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>";} ?>
Output:
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'));,
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>"; } ?>
Output:
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>";} }?>
Output:
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)
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); ?>
Output:
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...)
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"); ?>
Output:
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)
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"; } ?>
Output:
4. Array_pop() method
This method removes the last element from the given array.
Syntax
array_pop(array_name)
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); ?>
Output:
5. Array_push() method
This method adds given elements at the end of the array.
Syntax:
array_push(array_name, value1, value2, ...)
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); ?>
Output:
6. Array_shift() method
This method removes and returns the first element of the array.
Syntax:
array_shift(array_name)
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); ?>
Output:
7. Array_unshift() method
This method inserts given elements into the beginning of the array.
Syntax:
array_unshift(array_name, value1, value2,…)
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); ?>
Output:
8. Array_reverse() method
This method is used to reverse the elements of the array.
Syntax:
array_reverse(array_name, preserve)
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)); ?>
Output:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
