- PHP Array
- Introduction to PHP arrays
- Creating arrays
- 1) Creating an array using array() construct
- 2) Creating an array using the [] syntax
- Displaying arrays
- Accessing array elements
- Adding an element to the array
- Changing array elements
- Removing array elements
- Getting the size of an array
- Summary
- Get array index name in php
- Description
- Parameters
- Return Values
- Changelog
- Examples
- See Also
- User Contributed Notes 5 notes
PHP Array
Summary: in this tutorial, you’ll learn about PHP arrays and how to manipulate array elements effectively.
Introduction to PHP arrays
By definition, an array is a list of elements. So, for example, you may have an array that contains a list of products.
PHP provides you with two types of arrays: indexed and associative.
The keys of the indexed array are integers that start at 0. Typically, you use indexed arrays when you want to access the elements by their positions.
The keys of an associative array are strings. And you use associative arrays when you want to access elements by string keys.
This tutorial focuses on the indexed array.
Creating arrays
In PHP, you can use the array() construct or [] syntax to define an array. The [] syntax is shorter and more convenient.
1) Creating an array using array() construct
To define an array, you use the array() construct. The following example creates an empty array:
$empty_array = array();
Code language: HTML, XML (xml)
To create an array with some initial elements, you place a comma-separated list of elements within parentheses of the array() construct.
For example, the following defines an array that has three numbers:
$scores = array(1, 2, 3);
Code language: HTML, XML (xml)
2) Creating an array using the [] syntax
PHP provides a more convenient way to define arrays with the shorter syntax [], known as JSON notation. The following example uses [] syntax to create a new empty array:
$empty_array = [];
Code language: HTML, XML (xml)
The following example uses the [] syntax to create a new array that consists of three numbers:
$scores = [1, 2, 3];
Code language: HTML, XML (xml)
Displaying arrays
To show the contents of an array, you use the var_dump() function. For example:
$scores = [1, 2, 3]; var_dump($scores);
Code language: HTML, XML (xml)
array(3) < [0]=> int(1) [1]=> int(2) [2]=> int(3) >
Code language: PHP (php)
Or you can use the print_r() function:
$scores = array(1, 2, 3); print_r($scores);
Code language: HTML, XML (xml)
Array ( [0] => 1 [1] => 2 [2] => 3 )
Code language: PHP (php)
To make the output more readable, you can wrap the output of the print_r() function inside a tag. For example:
$scores = [1, 2, 3]; echo ''
; print_r($scores); echo '
';Code language: HTML, XML (xml)
Array ( [0] => 1 [1] => 2 [2] => 3 )
Code language: PHP (php)
It’s more convenient to define a function that prints out an array like this:
function print_array($data) < echo ''
; print_r($data); echo '
'; > $scores = [1, 2, 3]; print_array($scores);Code language: HTML, XML (xml)
Array ( [0] => 1 [1] => 2 [2] => 3 )
Code language: PHP (php)
And then you can reuse the function whenever you want to display an array.
Accessing array elements
To access an element in an array, you specify the index of the element within the square brackets:
$array_name[index]
Code language: PHP (php)
Note that the index of the first element of an array begins with zero, not one.
The following example shows how to access the first element of the array:
$scores = [1, 2, 3]; echo $scores[0];
Code language: HTML, XML (xml)
Adding an element to the array
To add an element to an array, you use the following syntax:
$array_name[] = new_element;
Code language: PHP (php)
PHP will calculate the highest numerical index plus one each time you assign an element to the array.
The following example shows how to add the number 4 to the $scores array:
$scores = [1, 2, 3]; $scores[] = 4;
Code language: HTML, XML (xml)
In this example, we defined an array that consists of three numbers initially. Then, we added the number 4 to the array.
It’s possible to use an index when you add a new element to the array. For example:
$scores = [1, 2, 3]; $scores[3] = 4;
Code language: PHP (php)
But doing this, you have to calculate the new index manually. It is not practical. Also, if the index is already is used, the value will be overwritten.
Changing array elements
The following statement changes the element located at the index to the $new_element :
$array_name[index] = $new_element;
Code language: PHP (php)
For example, to change the first element of the $scores array from 1 to zero, you do it as follows:
$scores = [1, 2, 3]; $scores[0] = 0;
Code language: HTML, XML (xml)
Removing array elements
To remove an element from an array, you use the unset() function. The following removes the second element of the $scores array:
$scores = [1, 2, 3]; unset($scores[1]);
Code language: HTML, XML (xml)
Getting the size of an array
To get the number of elements in an array, you use the count() function. For example:
$scores = [1, 2, 3, 4, 5]; echo count($scores);
Code language: HTML, XML (xml)
Summary
- Use the array() construct or [] syntax to create a new array.
- For the indexed array, the first index begins with zero.
- To access an array element, use an index in the square bracket $array_name[index] .
- Use the count() function to get the number of elements in an array.
Get array index name in php
key — Fetch a key from an array
Description
key() returns the index element of the current array position.
Parameters
Return Values
The key() function simply returns the key of the array element that’s currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns null .
Changelog
Version | Description |
---|---|
8.1.0 | Calling this function on object s is deprecated. Either convert the object to an array using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator , such as ArrayIterator , instead. |
7.4.0 | Instances of SPL classes are now treated like empty objects that have no properties instead of calling the Iterator method with the same name as this function. |
Examples
Example #1 key() example
$array = array(
‘fruit1’ => ‘apple’ ,
‘fruit2’ => ‘orange’ ,
‘fruit3’ => ‘grape’ ,
‘fruit4’ => ‘apple’ ,
‘fruit5’ => ‘apple’ );
?php
// this cycle echoes all associative array
// key where value equals «apple»
while ( $fruit_name = current ( $array )) if ( $fruit_name == ‘apple’ ) echo key ( $array ), «\n» ;
>
next ( $array );
>
?>
The above example will output:
See Also
- current() — Return the current element in an array
- next() — Advance the internal pointer of an array
- array_key_first() — Gets the first key of an array
- foreach
User Contributed Notes 5 notes
Note that using key($array) in a foreach loop may have unexpected results.
When requiring the key inside a foreach loop, you should use:
foreach($array as $key => $value)
I was incorrectly using:
foreach( $array as $value )
$mykey = key ( $array );
>
?>
and experiencing errors (the pointer of the array is already moved to the next item, so instead of getting the key for $value, you will get the key to the next value in the array)
CORRECT:
foreach( $array as $key => $value )
$mykey = $key ;
>
A noob error , but felt it might help someone else out there .
Suppose if the array values are in numbers and numbers contains `0` then the loop will be terminated. To overcome this you can user like this
while ( $fruit_name = current ( $array ))
echo key ( $array ). ‘
‘ ;
next ( $array );
>
// the way will be break loop when arra(‘2’=>0) because its value is ‘0’, while(0) will terminate the loop
// correct approach
while ( ( $fruit_name = current ( $array )) !== FALSE )
echo key ( $array ). ‘
‘ ;
next ( $array );
>
//this will work properly
?>
Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.
reset ( $x ); // optional.
arsort ( $x );
$key_of_max = key ( $x ); // returns the index.
?>
(Editor note: Or just use the array_keys function)
Make as simple as possible but not simpler like this one 🙂
In addition to FatBat’s response, if you’d like to find out the highest key in an array (assoc or not) but don’t want to arsort() it, take a look at this:
$arr = [ ‘3’ => 14 , ‘1’ => 15 , ‘4’ => 92 , ’15’ => 65 ];
$key_of_max = array_search ( max ( $arr ) , $arr );
- Array Functions
- array_change_key_case
- array_chunk
- array_column
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_is_list
- array_key_exists
- array_key_first
- array_key_last
- array_keys
- array_map
- array_merge_recursive
- array_merge
- array_multisort
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_replace_recursive
- array_replace
- array_reverse
- array_search
- array_shift
- array_slice
- array_splice
- array_sum
- array_udiff_assoc
- array_udiff_uassoc
- array_udiff
- array_uintersect_assoc
- array_uintersect_uassoc
- array_uintersect
- array_unique
- array_unshift
- array_values
- array_walk_recursive
- array_walk
- array
- arsort
- asort
- compact
- count
- current
- end
- extract
- in_array
- key_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
- each