QuestionsAnswered.net
What's Your Question?

What Is PHP Programming?
Want to learn more about what makes the web run? PHP is a programming language used for server-side web development. If this doesn’t make sense to you, or if you still aren’t quite sure what PHP programming is for, keep reading to learn more.
Understanding PHP
Web development topics can be pretty complicated for people who aren’t at least a little bit familiar with them, so it’s best to start with a simple explanation. In short, PHP is a server-side coding language that uses a format known as scripting. PHP is or has been behind some of the largest web businesses in the world, including Facebook and WordPress.
The Two Sides of Web Programming
The average website or app user doesn’t necessarily think that much about what goes on when they click a button, enter text in a box or scroll through results pages. Just a little bit of typing or clicking and information appears like magic. Of course, it isn’t magic. The clicking, scrolling and typing you do on the visible portion of a webpage is interaction with the website’s front end, or client side. All of the behind-the-scenes communication between different servers to retrieve and display information happens on the back end, or server side. PHP, a back-end language, isn’t about making things look nice the way front-end languages like CSS are.
Other Server-Side Languages
PHP is not the only server-side programming language out there. Others, like Ruby and Python, may be equally or more important in different situations. If you really want to gain an understanding of what PHP does and why, it may make sense to study up on these other languages as well. That doesn’t necessarily mean you need to master all three, but understanding the general function of server-side languages can provide extra context for PHP.
How to Learn PHP
Learning PHP requires some familiarity with how computer code and programming languages work. You can dive right into a free or paid PHP tutorial, but if you aren’t at least a little bit tech literate, you may be out of your depth. Tutorials often recommend that you learn HTML and CSS first. Learning PHP takes time and patience as you’ll need to not only understand the specifics of the language but also the tech jargon that surrounds it.
What Can You Do With PHP?
As a server-side language, PHP can allow you to do a lot of important work on a website’s back end. No, that’s not a double entendre. Back-end development is the process of building the unseen architecture that allows a website or app to function. For example, if you log into your bank account using a secure password, there’s a part of that transaction you see (e.g., the text boxes labelled “username” and “password”) and a part you don’t see, which involves communication of your request to a server, which verifies your username and password, deems them valid and allows you to proceed. All of that unseen communication is a server-side or back-end activity. So if you’re interested in the nitty gritty of what makes the web run rather than worrying about making things look nice and make sense for users, PHP would be a good language to learn. You may also want to learn other server-side languages so you can boost your capabilities and maybe even get a job in the tech industry.
MORE FROM QUESTIONSANSWERED.NET

- Function Reference
- Variable and Type Related Extensions
- Array Functions
(PHP 4, PHP 5, PHP 7, PHP 8)
array — Create an array
Description
Creates an array. Read the section on the array type for more information on what an array is.
Syntax "index => values", separated by commas, define index and values. index may be of type string or integer. When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1. Note that when two identical indices are defined, the last overwrites the first.
Having a trailing comma after the last defined array entry, while unusual, is a valid syntax.
Return Values
Returns an array of the parameters. The parameters can be given an index with the => operator. Read the section on the array type for more information on what an array is.
Example #1 array() example
Example #2 Automatic index with array()
The above example will output:
Note that index '3' is defined twice, and keep its final value of 13. Index 4 is defined after index 8, and next generated index (value 19) is 9, since biggest index was 8.
Example #3 1-based index with array()
Example #4 Accessing an array inside double quotes
Note : array() is a language construct used to represent literal arrays, and not a regular function.
- array_pad() - Pad array to the specified length with a value
- list() - Assign variables as if they were an array
- count() - Counts all elements in an array or in a Countable object
- range() - Create an array containing a range of elements
- The array type
User Contributed Notes 38 notes

PHP Tutorial
Php advanced, mysql database, php examples, php reference, php array() function.
❮ PHP Array Reference
Create an indexed array named $cars, assign three elements to it, and then print a text containing the array values:
Definition and Usage
The array() function is used to create an array.
In PHP, there are three types of arrays:
- Indexed arrays - Arrays with numeric index
- Associative arrays - Arrays with named keys
- Multidimensional arrays - Arrays containing one or more arrays
Syntax for indexed arrays:
Syntax for associative arrays:
Parameter Values
Technical details.
Advertisement
More Examples
Create an associative array named $age:
Loop through and print all the values of an indexed array:
Loop through and print all the values of an associative array:
Create a multidimensional array:

COLOR PICKER

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, get certified.
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- Labs The future of collective knowledge sharing
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
php array assign by copying value or by reference? [duplicate]
Possible Duplicate: are arrays in php passed by value or by reference?
I heard that PHP can select how to assign arrays, depends on array size. It can assign by copying value (as any scalar type) or by reference.
PHP always assign array to variables by copying a value, as it says in manual.
Or it can assign by reference. ?
- variable-assignment
- Are you just wanting to know if it's possible to assign an array by reference? Or do you want to know if there's some way to set it up to do that automatically? – jprofitt Jan 17, 2012 at 16:08
- i want to know, that sometimes PHp engine can pass $a = array(1,2,3); $b = $a; by reference without '&' sign. – RusAlex Jan 17, 2012 at 16:14
3 Answers 3
Assigning arrays by reference is possible when assigning array variables to other variables:

You can't assign something by reference unless you are referencing something that already exists. Equally, you can't copy something that doesn't exist.
So this code:
...neither copies or references - it just creates a new array fills it with values, because the values were specified literally.
However, this code:
...copies the values from $x , $y and $z into an array 1 . The variables used to initialise the array values still exist in their own right, and can be modified or destroyed without affecting the values in the array.
...creates an array of references to $x , $y and $z (notice the & ). If, after running this code, I modify $x - let's say I give it a value of 4 - it will also modify the first value in the array. So when you use the array, $a[0] will now contain 4 .
See this section of the manual for more information of how reference work in PHP.
1 Depending on the types and values of the variables used as the array members, the copy operation may not happen at the time of the assignment even when assigned by-value. Internally PHP uses copy-on-write in as many situations as possible for reasons of performance and memory efficiency. However, in terms of the behaviour in the context of your code, you can treat it as a simple copy.

Yes, use &
Not the answer you're looking for? Browse other questions tagged php arrays variable-assignment or ask your own question .
- The Overflow Blog
- Journey to the cloud part II: Migrating Stack Overflow for Teams to Azure
- Computers are learning to decode the language of our minds
- Featured on Meta
- Sunsetting Winter/Summer Bash: Rationale and Next Steps
- Discussions experiment launching on NLP Collective
- Temporary policy: Generative AI (e.g., ChatGPT) is banned
- Testing an "AI-generated content" policy banner on Stack Overflow
Hot Network Questions
- What's a good way to assert in embedded microcontroller code?
- When someone profits from injustice, is life less meaningful?
- What are some techniques for faster, fine-grained incremental compilation and static analysis?
- Inexplicable “The system cannot find the drive specified.” How to solve it?
- What is a good way to indicate that a number is not something you can count with?
- How long would it take for a civilization to forget how it began?
- Is a platform over a sump pump hole a solution to accessing electrical service?
- A Trivial Pursuit #04 (Art and Literature 1/4): Threesome
- How can I interpret it when correlation between two variables is significant, but not in a multiple regression?
- Cleaning up a string list
- Is it normal for an LED bulb to become hot to the touch?
- What kind of claims did Ryan Salame forfeit in the FTX trial?
- Are there any undecidability results that are not known to have a diagonal argument proof?
- Are there downsides to appealing?
- Does "want to be" mean 'tending to be so' or 'having such inclination'?
- Changing line height and line thickness with TikZ
- Did the Sun's light always peak in the green wavelengths?
- In principle, is it possible to create the sound of an instrument from the waveform of a different instrument?
- What plane was most likely used for this TWA transatlantic flight in 1954?
- Overwithholding due to wrong address
- I overstayed in South Korea, and now I want to go back to my home country (the US) after two months
- Why do metal finders not use any sensors other than search coils?
- What is the most common electronics IC package material?
- What divisive issues are least correlated with political alignment (e.g. whether you're on the left/right)?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
- Skip to main content
- Skip to primary sidebar
- Skip to footer
Matt Doyle | Elated Communications
Web and WordPress Development
Creating Arrays in PHP
10 March 2010 / 3 Comments
Like most programming languages, PHP lets you create arrays. An array is a special type of variable that can hold many values at once, all accessible via a single variable name. Arrays are very useful whenever you need to work with large amounts of data — such as records from a database — or group related data together.
In this article, you’ll:
- Learn how PHP arrays work, and why they’re useful
- Look at the difference between indexed arrays and associative arrays, and
- Learn how to create arrays within your PHP scripts.
How arrays work
As you’ve seen already, arrays are variables that can hold more than one value. Here are some more key facts about arrays in PHP:
- An array can hold any number of values, including no values at all.
- Each value in an array is called an element .
- You access each element via its index , which is a numeric or string value. Every element in an array has its own unique index.
- An element can store any type of value, such as an integer, a string, or a Boolean. You can mix types within an array — for example, the first element can contain an integer, the second can contain a string, and so on.
- An array’s length is the number of elements in the array.
- An array element’s value can itself be an array. This allows you to create multidimensional arrays .
Why arrays are useful
Arrays in PHP offer many benefits, including the following:
- They’re easy to manipulate. It’s easy to add or remove elements in an array, as well as read or change the value of an element.
- It’s easy to work with many values at once. You can easily loop through all elements in an array, reading or changing each element’s value as you move through the loop.
- PHP gives you many handy array-related functions. For example, you can sort array elements quickly and easily; search arrays for particular values or indices; and merge arrays together.
Indexed arrays and associative arrays
PHP lets you create 2 types of array:
- Indexed arrays have numeric indices. Typically the indices in an indexed array start from zero, so the first element has an index of 0 , the second has an index of 1 , and so on. Usually, you use an indexed array when you want to store a bunch of data in a certain order.
- A ssociative arrays have string indices. For example, one element of an associative array might have an index of "name" , while another element has an index of "age" . The order of the elements is usually unimportant. Typically, you use an associative array when you want to store records of data, much like using a database.
In fact, PHP doesn’t make any internal distinction between indexed and associative arrays. You can even mix numeric and string indices within the same array if you like. Most of the time, however, it helps to think of indexed and associative arrays as different types of arrays. Furthermore, many PHP array functions are designed to work with either indexed or associative arrays.
An associative array is sometimes referred to as a hash , and its indices are often called keys .
How to create an array in PHP
It’s easy to create an array within a PHP script. To create an array, you use the array() construct:
To create an indexed array, just list the array values inside the parentheses, separated by commas. The following example creates an indexed array of movie director names and stores it in a variable called $directors :
When creating an indexed array, PHP automatically assigns a numeric index to each element. In the above example, "Alfred Hitchcock" is given an index of 0 , "Stanley Kubrick" has an index of 1 , and so on.
To create an associative array, you pair each value with the index that you want to use for that value. To do this you use the => operator:
The following example creates an associative array with information about a movie, and stores it in a variable called $movie :
By the way, to create an array with no elements, you can write:
In this tutorial you’ve looked at the concept of arrays in PHP, and how to create them. In future tutorials I’ll show how to do stuff with arrays, such as add and remove elements, read and change element values, sort values in any order, and lots more.
Happy coding!
Reader Interactions
5 November 2019 at 10:38 pm
What if i’m trying to create an array of objects, how does that work?
2 October 2020 at 2:17 pm
i want to create an array with records from an ms sql server table
8 October 2020 at 12:23 am
Use PDO: https://www.php.net/manual/en/book.pdo.php
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.
Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .
Contact Matt
- Call Me: +61 2 8006 0622
Follow Matt
Copyright © 1996-2023 Elated Communications. All rights reserved. Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits
PHP Array – How to Use Arrays in Your PHP Projects
An array is a special variable that we use to store or hold more than one value in a single variable without having to create more variables to store those values.
To create an array in PHP, we use the array function array( ) .
By default, an array of any variable starts with the 0 index. So whenever you want to call the first value of an array you start with 0 then the next is 1 ...and so on.
There are different types of arrays in PHP. They are:
- Numeric/Indexed Arrays
- Associative Arrays
- Multidimensional Arrays
Let's look at how each one works in more detail.
What are Numerical or Indexed Arrays?
A numerical array is a type of array which can store strings, numbers, and objects. Here's an example of a numeric array:
From the code above I have a variable of $cars which stores an array of 5 elements. The var_dump($cars) keyword above will show us the total number of elements we have in the array, the index number of each array, and also the length of each element in the array.
You can also chose to use the echo( ) keyword, but in my case I prefer to use var_dump( ) because it gives a more detailed explanation of the results we get.

You can also choose to display only one element/item of an array in the web browser by doing this:
The code above follows the same pattern as our definition of an array, which states that it counts from zero. We want to display the element with the index of 4 . Counting from 0 to 4 , we can see that 88 falls under index 4 , indicating that 88 is the number we're seeking and that will be displayed to the browser.

What are Associative Arrays?
An associative array is a type of array where the key has its own value. In an associative array, we make use of key and value .
Key s are descriptive captions of the array element used to access the value of the array. And value is the value assigned to the array element.
There are situations where you shouldn't use the numeric/indexed array, such as:
- When you want to store the age of different students along with their names.
- When you want to record the salaries of your employees.
- When you want to store the score of a student in different subjects
and so on.
Suppose we want to assign ages to a group of high school students with their names.
We can use the Associative array method to get it done. For example:
The code above is an example of an associative array. The key s of the array are scott_Mcall , Stalenski , Lydia , Allision , and we used them to assign the age to each student. The value s of the array are 17 , 18 , 16 , and 17 .
What are Multidimensional Arrays?
You can think of a multidimensional array as an array of arrays. This means that every element in the array holds a sub-array within it. In general, multidimensional arrays allow you to store multiple arrays in a single variable.
Suppose we want to store the Names, Registration Numbers, and Emails of some of the staff working in a particular company. We can use multidimensional arrays to archive this.
For example:
Remember, an array starts counting from index 0 . The code above is an example of a multidimensional array because it contains more than one array (an array of arrays) with one single variable of $staff .
The echo $staff [2] [‘Email’] displays the email of the staff that falls into the index of 2 . In our case it will display [email protected] .
If I want to access the Email of the staff in the first array, we'll do the following:
echo $staff [0] ['Email'];
Using the method above, you can access and display any information in the array from the code above.
At this point you should be able to use the three different types of arrays when working on a PHP project.
Thank you for reading.
Have fun coding!
Hello, I go by the alias "Derek". I'm proficient in a wide range of technical skills, which I gained and continued to to hone through self-education.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
- PyQt5 ebook
- Tkinter ebook
- SQLite Python
- wxPython ebook
- Windows API ebook
- Java Swing ebook
- Java games ebook
- MySQL Java ebook
last modified January 10, 2023
In this article we show how to work with arrays in PHP.
We use PHP version 8.1.2.
PHP array definition
Arrays are collections of data. A variable can hold only one item at a time. Arrays can hold multiple items.
PHP has plenty of functions to modify, sort, merge, slice, shuffle the data inside the arrays. There are specific database handling functions for populating arrays from database queries. Several other functions return arrays.
PHP array initialization
Arrays can be initialized with a pair of [] brackets of with the array function.
We create a $names array, which stores five female names. The print_r function prints a human readable information about the variable.
From the output we can see the names and their indexes by which we can access them.
Traditionally, arrays have been initialized with the array function. In its simplest form, the function takes an arbitrary number of comma separated values.
Same array of female names is created with the array function.
Arrays can be initialized by assigning values to array indexes.
We create the $continents array by assigning values to array indexes. "America" has index 0, "Europe" has index 2 etc.
In this example, we create the $continents array with the indexes specified. By default, the first index is zero. In our case, we start with 1.
Now we have an array of continents with indexes that we have chosen.
The indexes do not have to be consecutive numbers.
In the example, we have chosen numbers 10, 20, 30, 40, and 50 to be the indexes for the $languages array.
When we do assignment initialization of a PHP array, we can omit the indexes. PHP automatically creates the indexes for us.
An array of actors is created. No specific indexes are set.
The PHP interpreter has created consecutive indexes starting from zero.
In this script, we have omitted two indexes. The PHP will add them. It will create index 12 and index 21.
PHP has automatically created indexes 12 and 21.
The keys of an array can be strings too.
We create a $countries array with string indexes.
PHP array element types
A PHP array can contain elements of various types.
In the example, we have an array with elements of different types. With the match expression and the gettype function, we get the type of each element.
PHP perusing arrays
Next we read the contents of the arrays. There are several ways how we can display data from an array.
We can access data from an array by their index.
We have printed all five languages to the console.
In this example, we use the for statement to peruse a $continents array.
First, we count the number of elements in the array with the count function.
The for loop prints elements from the array by indexes 0..$len-1.
The easiest way to peruse an array is to use the foreach statement. The statement goes through the array one by one and puts a current element to the temporary $continent variable. It accesses data without using their index or key.
In the last example, we use the array_walk function to peruse an array. It applies a user function to every member of an array. The user function takes the key and the value of the item as parameters.
We print both the key and the value to the console in the sentence.

PHP array sort
First we are going to sort an arrays.
In the above script, we have a $names array. We use the sort function to sort the contents of the array.
The output of the script shows unsorted and sorted female names.
The rsort function sorts an array in reverse order.
There is an array of integers. It is sorted in ascending and descending order.
The sort function sorts the integers in ascending order.
The rsort function sorts the integers in descending order.
In the following example, we show how to sort accented characters.
We have an array of Slovak words which contain specific accents.
We set the Slovak locale using the setlocale function. A locale represents a specific geographical, political, or cultural region.
The $words is an array of accented Slovak words.
We sort the array in ascending order with the sort function. We pass the SORT_LOCALE_STRING flag to the function, which tells sort to take the locale into account.
The words are correctly sorted according to the Slovak standards.
Sometimes we need to perform custom sorting. For custom sorting, we have the usort function in PHP.
We have an array of full names. The sort function would sort these strings according to the first names, because they precede the second names. We create a solution to sort these names according to their second names.
We have a custom sorting function. The names are split by the explode function and the second names are compared with the strcmp function.
The usort function accepts the comparing function as its second parameter.
The names are correctly sorted according to their second names.
PHP counting values in arrays
The count function counts the number of elements in the array. The array_sum function calculates the sum of all values. The array_product function calculates the product of values in the array.
In the example, we have an array of numbers. We apply the above defined functions on the array.
PHP unique values
In the following example, we find out unique values in an array.
In this script, we have duplicates in the array. The array_count_values function returns an array with the number of occurrences for each value. The array_unique function returns an array without duplicates.
The first array says that 3 is present twice, 4 three times, and 2 once. The second array says that there are three values present in the array: 3, 4, and 2. Value 3 has index 0, 4 has index 1 and 2 has index 4. The array_unique function keeps the indexes untouched.
PHP slicing arrays
The array_slice function returns a sequence of elements from an array as specified by its offset and length parameters.
In the example, we create two slices of an array of integers.
We create a slice starting from the first element; the length of the slice is three elements.
By giving a negative offset, the slice is created from the end of the array.
PHP array pointer
PHP has an internal array pointer. In the following example, we present functions that manipulate this pointer.
In this example, we traverse the array using the functions that move the internal array pointer.
The current function returns the current element in the array. At the beginning, it is the first element of the array. The next function advances the pointer by one position. The end function returns the last element. The prev element returns the element, one position before the current one. In our case it is the next to the last element.
Here we use the reset function to set the internal pointer to the first element again and peruse the $continents array one more time.
PHP merging arrays
The array_merge function merges arrays.
In this example, we have two arrays: $names1 and $names2 . We use the array_merge function to create $names array by merging the previous two arrays.
The new array has six names.
PHP modifying arrays
It is possible to modify PHP arrays with array_push , array_pop , array_shift , or array_unshift functions.
In the above script, we use functions that modify the contents of an array. We have a $numbers array that has 4 numbers: 1, 2, 3, and 4.
The array_push function inserts one or more items to the end of the array. Our array now contains values 1, 2, 3, 4, 5, and 6.
The array_pop function removes the last item from the array. Our array stores now numbers 1, 2, 3, 4, and 5.
The array_unshift function adds -1 and 0 to the beginning of the array. The array contains values -1, 0, 1, 2, 3, 4, and 5.
Finally, the array_shift function removes the first item from the array. Now we have values 0, 1, 2, 3, 4, and 5 in the array.
PHP range function
The range function simplifies array creation by automatically creating a sequence of elements. It accepts three parameters: start of sequence, end of sequence, and an optional increment, which defaults to 1.
The range function enables us to create a list of consecutive numbers easily.
An array with numbers 1, 2, ... 15 is created.
It is possible to create a descending sequence of values by specifying a negative increment.
PHP randomizing array values
The array_rand function picks one or more random entries from an array. The shuffle function randomizes the order of the elements in an array.
In the example, we pick random values from the array and randomize its order of elements.
The array_rand function returns a random key from the $num array.
In this case, the array_rand function returns an array of two random keys.
This is a sample output of the randomize.php program.
PHP in_array function
The in_array function checks if a specific element is inside an array.
Our script checks if 'Jane' and 'Monica' is in the $names array.
'Jane is in the array, but 'Monica' is not.
PHP array keys and values
PHP array is an associative array which consists of key and value pairs.
The array_keys function returns all the keys of an array. The array_values function returns all the values of an array.
The first line consists of top level domain names. These were the keys of the $domains array. The second line are the names of the corresponding countries. These were the values of the array.
PHP array_walk function
The array_walk function applies a user defined function to every member of the array.
We have a $countries array. We apply the show_values function to each element of the array. The function simply prints the key and the value for each element.
In this article we have covered PHP arrays.
My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.
List all PHP tutorials.
Learning PHP 5 by David Sklar
Get full access to Learning PHP 5 and 60K+ other titles, with a free 10-day trial of O'Reilly.
There are also live events, courses curated by job role, and more.
Chapter 4. Working with Arrays
Arrays are collections of related values, such as the data submitted from a form, the names of students in a class, or the populations of a list of cities. In Chapter 2 , you learned that a variable is a named container that holds a value. An array is a container that holds multiple values, each distinct from the rest.
This chapter shows you how to work with arrays. Section 4.1 , next, goes over fundamentals such as how to create arrays and manipulate their elements. Frequently, youâll want to do something with each element in an array, such as print it or inspect it for certain conditions. Section 4.2 explains how to do these things with the foreach( ) and for( ) constructs. Section 4.3 introduces the implode( ) and explode( ) functions, which turn arrays into strings and strings into arrays. Another kind of array modification is sorting, which is discussed in Section 4.4 . Last, Section 4.5 explores arrays that themselves contain other arrays.
Chapter 6 shows you how to process form data, which the PHP interpreter automatically puts into an array for you. When you retrieve information from a database as described in Chapter 7 , that data is often packaged into an array.
Array Basics
An array is made up of elements . Each element has a key and a value . An array holding information about the colors of vegetables has vegetable names for keys and colors for values, shown in Figure 4-1 .
An array can only have one element with a given key. In the vegetable color array, there canât be another element with the key corn even if its value is blue . However, the same value can appear many times in one array. You can have orange carrots, orange tangerines, and orange oranges.
Any string or number value can be an array element key such as corn , 4 , -36 , or Salt Baked Squid . Arrays and other nonscalar [ 1 ] values canât be keys, but they can be element values. An element value can be a string, a number, true , or false ; it can also be another array.
Creating an Array
To create an array, assign a value to a particular array key. Array keys are denoted with square brackets, as shown in Example 4-1 .
The array keys and values in Example 4-1 are strings (such as corn , Braised Bamboo Fungus , and Coleco ) and numbers (such as 0 , 1 , and 2600 ). They are written just like other strings and numbers in PHP programs: with quotes around the strings but not around the numbers.
You can also create an array using the array( ) language construct. Example 4-2 creates the same arrays as Example 4-1 .
With array( ) , you specify a comma-delimited list of key/value pairs. The key and the value are separated by => . The array( ) syntax is more concise when you are adding more than one element to an array at a time. The square bracket syntax is better when you are adding elements one by one.
Choosing a Good Array Name
Array names follow the same rules as variable names. The first character of an array name must be a letter or number, and the rest of the characters of the name must be letters, numbers, or the underscore. Names for arrays and scalar variables come from the same pool of possible names, so you canât have an array called $vegetables and a scalar called $vegetables at the same time. If you assign an array value to a scalar or vice versa, then the old value is wiped out and the variable silently becomes the new type. In Example 4-3 , $vegetables becomes a scalar, and $fruits becomes an array.
In Example 4-1 , the $vegetables and $computers arrays store a list of relationships. The $vegetables array relates vegetables and colors, while the $computers array relates computer names and manufacturers. In the $dinner array, however, we just care about the names of dishes that are the array values. The array keys are just numbers that distinguish one element from another.
Creating a Numeric Array
PHP provides some shortcuts for working with arrays that have only numbers as keys. If you create an array with array( ) by specifying only a list of values instead of key/value pairs, the PHP interpreter automatically assigns a numeric key to each value. The keys start at 0 and increase by 1 for each element. Example 4-4 uses this technique to create the $dinner array.
Example 4-4 prints:
Internally, the PHP interpreter treats arrays with numeric keys and arrays with string keys (and arrays with a mix of numeric and string keys) identically. Because of the resemblance to features in other programming languages, programmers often refer to arrays with only numeric keys as ânumeric,â âindexed,â or âorderedâ arrays, and to string-keyed arrays as âassociativeâ arrays. An associative array , in other words, is one whose keys signify something other than the positions of the values within the array.
PHP automatically uses incrementing numbers for array keys when you create an array or add elements to an array with the empty brackets syntax shown in Example 4-5 .
The empty brackets add an element to the array. The element has a numeric key thatâs one more than the biggest numeric key already in the array. If the array doesnât exist yet, the empty brackets add an element with a key of 0 .
Making the first element have key 0 , not key 1 , is the exact opposite of how normal humans (in contrast to computer programmers) think, so it bears repeating. The first element of an array with numeric keys is element 0 , not element 1 .
Finding the Size of an Array
The count( ) function tells you the number of elements in an array. Example 4-6 demonstrates count( ) .
Example 4-6 prints:
When you pass it an empty array (that is, an array with no elements in it), count( ) returns 0. An empty array also evaluates to false in an if( ) test expression.
Looping Through Arrays
One of the most common things to do with an array is to consider each element in the array individually and process it somehow. This may involve incorporating it into a row of an HTML table or adding its value to a running total.
The easiest way to iterate through each element of an array is with foreach( ) . The foreach( ) construct lets you run a code block once for each element in an array. Example 4-7 uses foreach( ) to print an HTML table containing each element in an array.
Example 4-7 prints:
For each element in $meal , foreach( ) copies the key of the element into $key and the value into $value . Then, it runs the code inside the curly braces. In Example 4-7 , that code prints $key and $value with some HTML to make a table row. You can use whatever variable names you want for the key and value inside the code block. If the variable names were in use before the foreach( ) , though, theyâre overwritten with values from the array.
When youâre using foreach( ) to print out data in an HTML table, often you want to apply alternating colors or styles to each table row. This is easy to do when you store the alternating color values in a separate array. Then, switch a variable between 0 and 1 each time through the foreach( ) to print the appropriate color. Example 4-8 alternates between the two color values in its $row_color array.
Example 4-8 prints:
Inside the foreach( ) code block, changing the loop variables like $key and $value doesnât affect the actual array. If you want to change the array, use the $key variable as an index into the array. Example 4-9 uses this technique to double each element in the array.
Example 4-9 prints:
Thereâs a more concise form of foreach( ) for use with numeric arrays, shown in Example 4-10 .
Example 4-10 prints:
With this form of foreach( ) , just specify one variable name after as , and each element value is copied into that variable inside the code block. However, you canât access element keys inside the code block.
To keep track of your position in the array with foreach( ) , you have to use a separate variable that you increment each time the foreach( ) code block runs. With for( ) , you get the position explicitly in your loop variable. The foreach( ) loop gives you the value of each array element, but the for( ) loop gives you the position of each array element. Thereâs no loop structure that gives you both at once.
So, if you want to know what element youâre on as youâre iterating through a numeric array, use for( ) instead of foreach( ) . Your for( ) loop should depend on a loop variable that starts at 0 and continues up to one less than the number of elements in the array. This is shown in Example 4-11 .
Example 4-11 prints:
When iterating through an array with for( ) , you have a running counter available of which array element youâre on. Use this counter with the modulus operator to alternate table row colors, as shown in Example 4-12 .
Example 4-12 computes the correct table row color with $i % 2 . This value alternates between 0 and 1 as $i alternates between even and odd. Thereâs no need to use a separate variable, such as $color_index in Example 4-8 , to hold the appropriate row color. Example 4-12 prints:
When you iterate through an array using foreach( ) , the elements are accessed in the order that they were added to the array. The first element added is accessed first, the second element added is accessed next, and so on. If you have a numeric array whose elements were added in a different order than how their keys would usually be ordered, this could produce unexpected results. Example 4-13 doesnât print out array elements in numeric or alphabetic order.
Example 4-13 prints:
To guarantee that elements are accessed in numerical key order, use for( ) to iterate through the loop:
This prints:
If youâre looking for a specific element in an array, you donât need to iterate through the entire array to find it. There are more efficient ways to locate a particular element. To check for an element with a certain key, use array_key_exists( ) , shown in Example 4-14 . This function returns true if an element with the provided key exists in the provided array.
To check for an element with a particular value, use in_array( ) , as shown in Example 4-15 .
The in_array( ) function returns true if it finds an element with the given value. It is case-sensitive when it compares strings. The array_search( ) function is similar to in_array( ) , but if it finds an element, it returns the element key instead of true . In Example 4-16 , array_search( ) returns the name of the dish that costs $6.50.
Example 4-16 prints:
Modifying Arrays
You can operate on individual array elements just like regular scalar variables, using arithmetic, logical, and other operators. Example 4-17 shows some operations on array elements.
Example 4-17 prints:
Interpolating array element values in double-quoted strings or here documents is similar to interpolating numbers or strings. The easiest way is to include the array element in the string, but donât put quotes around the element key. This is shown in Example 4-18 .
Example 4-18 prints:
The interpolation in Example 4-18 works only with array keys that consist exclusively of letters, numbers, and underscores. If you have an array key that has whitespace or other punctuation in it, interpolate it with curly braces, as demonstrated in Example 4-19 .
Example 4-19 prints:
In a double-quoted string or here document, an expression inside curly braces is evaluated and then its value is put into the string. In Example 4-19 , the expressions used are lone array elements, so the element values are interpolated into the strings.
To remove an element from an array, use unset( ) :
Removing an element with unset( ) is different than just setting the element value to 0 or the empty string. When you use unset( ) , the element is no longer there when you iterate through the array or count the number of elements in the array. Using unset( ) on an array that represents a storeâs inventory is like saying that the store no longer carries a product. Setting the elementâs value to 0 or the empty string says that the item is temporarily out of stock.
When you want to print all of the values in an array at once, the quickest way is to use the implode( ) function. It makes a string by combining all the values in an array and separating them with a string delimiter. Example 4-20 prints a comma-separated list of dim sum choices.
Example 4-20 prints:
To implode an array with no delimiter, use the empty string as the first argument to implode( ) :
Use implode( ) to simplify printing HTML table rows, as shown in Example 4-21 .
Example 4-21 prints:
The implode( ) function puts its delimiter between each value, so to make a complete table row, you also have to print the opening tags that go before the first element and the closing tags that go after the last element.
The counterpart to implode( ) is called explode( ) . It breaks a string apart into an array. The delimiter argument to explode( ) is the string it should look for to separate array elements. Example 4-22 demonstrates explode( ) .
Example 4-22 prints:
Sorting Arrays
There are several ways to sort arrays. Which function to use depends on how you want to sort your array and what kind of array it is.
The sort( ) function sorts an array by its element values. It should only be used on numeric arrays, because it resets the keys of the array when it sorts. Example 4-23 shows some arrays before and after sorting.
Example 4-23 prints:
Both arrays have been rearranged in ascending order by element value. The first value in $dinner is now Braised Bamboo Fungus , and the first value in $meal is Cashew Nuts and White Mushrooms . The keys in $dinner havenât changed because it was a numeric array before we sorted it. The keys in $meal , however, have been replaced by numbers from 0 to 3 .
To sort an associative array by element value, use asort( ) . This keeps keys together with their values. Example 4-24 shows the $meal array from Example 4-23 sorted with asort( ) .
Example 4-24 prints:
The values are sorted in the same way with asort( ) as with sort( ) , but this time, the keys stick around.
While sort( ) and asort( ) sort arrays by element value, you can also sort arrays by key with ksort( ) . This keeps key/value pairs together, but orders them by key. Example 4-25 shows $meal sorted with ksort( ) .
Example 4-25 prints:
The array is reordered so the keys are now in ascending alphabetical order. Each element is unchanged, so the value that went with each key before the sorting is the same as each key value after the sorting. If you sort a numeric array with ksort( ) , then the elements are ordered so the keys are in ascending numeric order. This is the same order you start out with when you create a numeric array using array( ) or [ ] .
The array sorting functions sort( ) , asort( ) , and ksort( ) have counterparts that sort in descending order. The reverse-sorting functions are named rsort( ) , arsort( ) , and krsort( ) . They work exactly as sort( ) , asort( ) , and ksort( ) except they sort the arrays so the largest (or alphabetically last) key or value is first in the sorted array, and so subsequent elements are arranged in descending order. Example 4-26 shows arsort( ) in action.
Example 4-26 prints:
Using Multidimensional Arrays
As mentioned earlier in Section 4.1 , the value of an array element can be another array. This is useful when you want to store data that has a more complicated structure than just a key and a single value. A standard key/value pair is fine for matching up a meal name (such as breakfast or lunch ) with a single dish (such as Walnut Bun or Chicken with Cashew Nuts ), but what about when each meal consists of more than one dish? Then, element values should be arrays, not strings.
Use the array( ) construct to create arrays that have more arrays as element values, as shown in Example 4-27 .
Access elements in these arrays of arrays by using more sets of square brackets to identify elements. Each set of square brackets goes one level into the entire array. Example 4-28 demonstrates how to access elements of the arrays defined in Example 4-27 .
Each level of an array is called a dimension . Before this section, all the arrays in this chapter are one-dimensional arrays . They each have one level of keys. Arrays such as $meals , $lunches , and $flavors , shown in Example 4-28 , are called multidimensional arrays because they each have more than one dimension.
You can also create or modify multidimensional arrays with the square bracket syntax. Example 4-29 shows some multidimensional array manipulation.
To iterate through each dimension of a multidimensional array, use nested foreach( ) or for( ) loops. Example 4-30 uses foreach( ) to iterate through a multidimensional associative array.
Example 4-30 prints:
The first foreach( ) loop in Example 4-30 iterates through the first dimension of $flavors . The keys stored in $culture are the strings Japanese and Chinese , and the values stored in $culture_flavors are the arrays that are the element values of this dimension. The next foreach( ) iterates over those element value arrays, copying keys such as hot and salty into $flavor and values such as wasabi and soy sauce into $example . The code block of the second foreach( ) uses variables from both foreach( ) statements to print out a complete message.
Just like nested foreach( ) loops iterate through a multidimensional associative array, nested for( ) loops iterate through a multidimensional numeric array, as shown in Example 4-31 .
Example 4-31 prints:
In Example 4-31 , the outer for( ) loop iterates over the two elements of $specials . The inner for( ) loop iterates over each element of the subarrays that hold the different strings. In the print statement, $i is the index in the first dimension (the elements of $specials ), and $m is the index in the second dimension (the subarray).
To interpolate a value from a multidimensional array into a double-quoted string or here document, use the curly brace syntax from Example 4-19 . Example 4-32 uses curly braces for interpolation to produce the same output as Example 4-31 . In fact, the only different line in Example 4-32 is the print statement.
Chapter Summary
Chapter 4 covers:
Understanding the components of an array: elements, keys, and values.
Defining an array in your programs two ways: with array( ) and with square brackets.
Understanding the shortcuts PHP provides for arrays with numeric keys.
Counting the number of elements in an array.
Visiting each element of an array with foreach( ) .
Alternating table row colors with foreach( ) and an array of color values.
Modifying array element values inside a foreach( ) code block.
Visiting each element of a numeric array with for( ) .
Alternating table row colors with for( ) and the modulus operator ( % ).
Understanding the order in which foreach( ) and for( ) visit array elements.
Checking for an array element with a particular key.
Checking for an array element with a particular value.
Interpolating array element values in strings.
Removing an element from an array.
Generating a string from an array with implode( ) .
Generating an array from a string with explode( ) .
Sorting an array with sort( ) , asort( ) , or ksort( ) .
Sorting an array in reverse.
Defining a multidimensional array.
Accessing individual elements of a multidimensional array.
Visiting each element in a multidimensional array with foreach( ) or for( ) .
Interpolating multidimensional array elements in a string.
According to the U.S. Census Bureau, the 10 largest American cities (by population) in 2000 were as follows:
New York, NY (8,008,278 people)
Los Angeles, CA (3,694,820)
Chicago, IL (2,896,016)
Houston, TX (1,953,631)
Philadelphia, PA (1,517,550)
Phoenix, AZ (1,321,045)
San Diego, CA (1,223,400)
Dallas, TX (1,188,580)
San Antonio, TX (1,144,646)
Detroit, MI (951,270)
Define an array (or arrays) that holds this information about locations and population. Print a table of locations and population information that includes the total population in all 10 cities.
Modify your solution to the previous exercise so that the rows in result table are ordered by population. Then modify your solution so that the rows are ordered by city name.
Modify your solution to the first exercise so that the table also contains rows that hold state population totals for each state represented in the list of cities.
For each of the following kinds of information, state how you would store it in an array and then give sample code that creates such an array with a few elements. For example, for the first item, you might say, âAn associative array whose key is the studentâs name and whose value is an associative array of grade and ID number,â as in the following:
The grades and ID numbers of students in a class.
How many of each item in a store inventory is in stock.
School lunches for a week â the different parts of each meal (entree, side dish, drink, etc.) and the cost for each day.
The names of people in your family.
The names, ages, and relationship to you of people in your family.
[ 1 ] Scalar describes data that has a single value: a number, a piece of text, true, or false. Complex data types such as arrays, which hold multiple values, are not scalars.
Get Learning PHP 5 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.
Don’t leave empty-handed
Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.
It’s yours, free.

Check it out now on O’Reilly
Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

Mastering PHP arrays: Array basics
An array is one of the most powerful and flexible data types in PHP.
Arrays are ordered collections of items, called array elements, and are actually an implementation of ordered maps or more precisely hash tables .
Arrays are flexible in defining keys and values. They are capable of storing any value, including other arrays, trees and multidimensional arrays. Every value has its key although it is not defined implicitly by its definition.
Creating arrays
An array can be created using the array() language construct or as of PHP 5.4 short array syntax [] . Array elements can be assigned to variable in multiple ways:
Variables $array1 and $array2 have assigned empty array. Variable $array2 has an empty array value assigned by short syntax.
Variable $array1 is filled with values 11 , 2 and 0 afterwards. These values are appended to the empty array using assign operator and square bracket syntax: array[key] = value . Since every member of an array must have a key, a numeric key starting from 0 is assigned to every element automatically.
An array construct enables to fill the array with values at its creation using index => value syntax separated by commas. When an index is omitted, the integer index is automatically generated. The variable $array3 is created using array construct parameters and it’s identical to the $array1 .
Variable $array4 is created using short array syntax and it’s filled with mixed key data types. The last element of the array has a trailing comma. While unusual, it is a valid syntax. It’s a good practice to leave a trailing comma in multiline array definitions.
PHP supports only integer and strings keys. Other data types are cast to these two based on casting rules.
Handling array keys
Array keys are unique values and can be either integers or strings. Data type other then this will be cast to these data types by following casting rules:
Note that array keys are case-sensitive but type insensitive and elements with same keys are overwritten with a later declaration. Arrays are type insensitive because they are using a special type of hash table called symtable . Integers and numeric strings in a symtable are considered identical and because of this value stored in an array as $array['1'] can be also accessed as $array[1] .
Typecasting and overwriting example:
Finally this array will contain only element with key 0 and value 'orange' and element with key 1 and value 'melon' .
Arrays are limited by implementation of hash tables and its maximum number of elements, and the memory_limit . The maximum number of elements depends on OS architecture. Enumerative arrays are also limited by the maximum size of an integer.
Let’s consider this example:
An array from the example above will look like this:
After the PHP_INT_MAX limit was exceeded, overflow happened and a value with a key -9223372036854775808 was overwritten with the later declaration of the value.
Enumerative vs. Associative arrays
Arrays can roughly be divided into two categories:
- Enumerative: indexed using only numerical indexes
- Associative: indexed using arbitrary indexes
PHP arrays can contain integer and string keys at the same time as PHP does not distinguish between indexed and associative arrays. This enables to create an enumerative array, insert associative element to it and PHP will still maintain elements of an enumeration.
Let’s see an example:
After an associative element was added, PHP automatically assigned a numeric key to the next element, which is equal to the greatest existing numeric key plus one. Note that array keys are indexed from 0 and they don’t determine the order of its elements. PHP is maintaining the array order by its internal pointer.
Because there is no correlation between the array pointer and element keys. We can insert elements with keys which are not sequential:
PHP automatically assigned a numeric key 11 ( 10+1 ) to the value 2000 .
Printing arrays
To debug a script, it is often needed to output variable values. PHP provides 2 functions which are capable to do this:
- print_r() : displays information in a way that’s readable by humans; capable to return the information rather than print it (capturing output)
- var_dump() : displays structured information that includes its type and value; capable of outputting multiple variables at the same time
The example above will output:
Array reconstruction
PHP also provides var_export() , a function which outputs or returns structured information about the given variable. The returned value is a valid PHP code and can be used for reconstruction.
Note missing trailing semicolon.
Accessing array elements
Array elements can be accessed using the square bracket syntax: array[key] .
This will output:
Now we can access array elements like this:
Which will output:
Array elements can be also accessed using curly braces similar to square brackets. Both of them do the same thing (e.g. $array['beverage']['alcoholic'] and $array{'beverage'}{'alcoholic'} ). Elements can be accessed even using mixed syntax (e.g. $array{'beverage'}['alcoholic'] ).
The square bracket syntax is more commonly used.
Deleting arrays and removing array elements
To remove a key-value pair or delete a whole array use the function unset() :
Destroying the whole array:
An array can be also removed by overwriting with null :
This will have similar effect to the unset() .
Determining arrays
Array variables can be determined using is_array() function. This function finds whether the given variable is an array and returns a boolean value.
The above example will output:
Determining associative and enumerative arrays
Sometimes it’s needed to determine whether an array has only numeric keys or is associative. PHP does not distinguish between indexed and associative arrays and handles both types in the same way. There is no native function to do this, but there is an elegant solution .
To determine whether an array is associative or not this function can be used:
Example usage of the is_assoc() function:
The above code example will output:
The is_assoc() function is using an array function which extracts array keys using the array_keys() function. The output is subsequently filtered using the array_filter() function with the is_string() function as a callback. If at least one of array keys contains string, true is returned or false is returned otherwise. Count of keys containing string is determined using the count() function and subsequently casted to a boolean value using (bool) .
An enumerative array can be determined using negation if this function or creating a new function similar to this one using a different filter callback function.
Comparing arrays
Arrays can be compared using equality operator == or identity operator === :
In both comparison types keys and values are compared. The two arrays are equal when each of them contain the same key-value associations. The identity operator examines also order of an array elements.
Sometimes it’s needed to compare only keys or values. This can be done using same comparison methods as the above and one of the array_keys() or array_values() function:
Note that the array_keys() and the array_values() function is reindexing original array keys.
Unravelling and dereferencing arrays
Array elements are often assigned to variables. This can be done using one of accessing methods individually or using list() construct shortcut:
Note that list() assigns values starting with the right-most parameter and works only on numerical keys.
Array elements can be omitted using multiple commas:
As of PHP 5.4, it is possible to access array members directly when an array is returned by a function. This is known as array dereferencing. As of PHP 5.5, it is also possible to array dereference an array literal.
Further reading
- http://php.net/manual/en/language.types.array.php
- https://nikic.github.io/2012/03/28/Understanding-PHPs-internal-array-implementation.html
- http://en.wikipedia.org/wiki/Hash_table
- Previous Mastering PHP arrays: Array sorting
- Next Linux Filesystem

IMAGES
VIDEO
COMMENTS
In the world of web development, developers have a wide array of options when it comes to scripting languages, data retrieval, and other details. As a result, a plethora of combinations do exist. However, using PHP and MySQL in web developm...
Want to learn more about what makes the web run? PHP is a programming language used for server-side web development. If this doesn’t make sense to you, or if you still aren’t quite sure what PHP programming is for, keep reading to learn mor...
According to Purdue University’s website, the abbreviation for the word “assignment” is ASSG. This is listed as a standard abbreviation within the field of information technology.
An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments. array( key =>
Notice that you can also add arrays to other arrays with the $array[] "operator" while the dimension doesn't matter. Here's an example: $x[w][x] = $y[y][z];
PHP array() Function ; Create an indexed array named $cars, assign three elements to it, and then print a text containing the array values: · ("Volvo","BMW"
Assigning arrays by reference is possible when assigning array variables to other variables: // By value... $a = array(1,2,3); $b = $a;
To create an array, you use the array() construct: $myArray = array( values );. To create an indexed array, just list the array values inside
To create an array in PHP, we use the array function array( ) . By default, an array of any variable starts with the 0 index.
Arrays are collections of data. A variable can hold only one item at a time. Arrays can hold multiple items. Note: a PHP array is a collection
$Order_Number = array( );. First you type out what you want your array to be called ($Order_Number, in the array above) and, after an equals sign, you
In this tutorial, I am going to make a list of common PHP array functions, with examples ... is designed to assign variables in a short way.
If you create an array with array( ) by specifying only a list of values instead of key/value pairs, the PHP interpreter automatically assigns a numeric key
These values are appended to the empty array using assign operator and square bracket syntax: array[key] = value .