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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool