Multi dimensional array php

PHP Multidimensional Array

Summary: in this tutorial, you will learn how to define a PHP multidimensional array and manipulate its elements effectively.

Introduction to PHP multidimensional array

Typically, you have an array with one dimension. For example:

 $scores = [1, 2, 3, 4, 5];Code language: HTML, XML (xml)
 $rates = [ 'Excellent' => 5, 'Good' => 4, 'OK' => 3, 'Bad' => 2, 'Very Bad' => 1 ];Code language: HTML, XML (xml)

Both $scores and $rates are one-dimensional arrays.

A multidimensional array is an array that has more than one dimension. For example, a two-dimensional array is an array of arrays. It is like a table of rows and columns.

In PHP, an element in an array can be another array. Therefore, to define a multidimensional array, you define an array of arrays.

The following example uses an array of arrays to define a two-dimensional array:

 $tasks = [ ['Learn PHP programming', 2], ['Practice PHP', 2], ['Work', 8], ['Do exercise' 1], ];Code language: HTML, XML (xml)

In the $tasks array, the first dimension represents the tasks and the second dimension specifies hour spent for each.

To dispaly all the elements in a multidimensional array, you use the print_r() function like this:

 $tasks = [ ['Learn PHP programming', 2], ['Practice PHP', 2], ['Work', 8], ['Do exercise', 1], ]; print_r($todo_list);Code language: HTML, XML (xml)
Array ( [0] => Array ( [0] => Learn PHP programming [1] => 2 ) [1] => Array ( [0] => Practice PHP [1] => 2 ) [2] => Array ( [0] => Work [1] => 8 ) [3] => Array ( [0] => Do exercise [1] => 1 ) )Code language: PHP (php)

Adding elements to a PHP multidimensional array

To add an element to a multidimensional array, you use the the following syntax:

 $array[] = [element1, element2, . ];Code language: HTML, XML (xml)

For example, to add an element at the end of the $tasks array, you use the following:

 $tasks = [ ['Learn PHP programming', 2], ['Practice PHP', 2], ['Work', 8], ['Do exercise', 1], ]; $tasks[] = ['Build something matter in PHP', 2]; print_r($tasks );Code language: HTML, XML (xml)

Removing elements from a PHP multidimensional array

To remove an element from a multidimensional array, you can use the unset() function.

The following example uses the unset() function to remove the third element of the $tasks array:

 $tasks = [ ['Learn PHP programming', 2], ['Practice PHP', 2], ['Work', 8], ['Do exercise',1], ]; unset($tasks[2]); print_r($tasks);Code language: HTML, XML (xml)
Array ( [0] => Array ( [0] => Learn PHP programming [1] => 2 ) [1] => Array ( [0] => Practice PHP [1] => 2 ) [3] => Array ( [0] => Do exercise [1] => 1 ) )Code language: PHP (php)

Note that the unset() function doesn’t change the array’s keys. To reindex the key, you can use the array_splice() function. For example:

 $tasks = [ ['Learn PHP programming', 2], ['Practice PHP', 2], ['Work', 8], ['Do exercise', 1], ]; array_splice($tasks[2], 2, 1); print_r($tasks);Code language: HTML, XML (xml)
Array ( [0] => Array ( [0] => Learn PHP programming [1] => 2 ) [1] => Array ( [0] => Work [1] => 8 ) [2] => Array ( [0] => Do exercise [1] => 1 ) )Code language: PHP (php)

Iterating over elements of a multidimensional array using foreach

To iterate a multidimensional array, you use a nested foreach loop like this:

 $tasks = [ ['Learn PHP programming', 2], ['Practice PHP', 2], ['Work', 8], ['Do exercise', 1], ]; foreach ($tasks as $task) < foreach ($task as $task_detail) < echo $task_detail . '
'
; > >
Code language: HTML, XML (xml)
Learn PHP programming 2 Practice PHP 2 Work 8 Do exercise 1Code language: PHP (php)

Accessing elements of a multidimensional array

To access an element in an multidimensional array, you use the square brackets ( [] ):

 $arrayMulti dimensional array phpMulti dimensional array phpMulti dimensional array php. Code language: HTML, XML (xml)

For example, to access the number of hour spent for the «Learn PHP programming» task, you use the following code:

 $tasks = [ ['Learn PHP programming', 2], ['Practice PHP', 2], ['Work', 8], ['Do excercise', 1], ]; echo $tasks[0][1];Code language: HTML, XML (xml)

Sorting a multidimensional array

To sort a multidimensional array, you use the usort() function. For example:

 $tasks = [ ['Learn PHP programming', 2], ['Practice PHP', 2], ['Work', 8], ['Do excercise', 1], ]; usort($tasks, function ($a, $b) < return $a[1] $b[1]; >); print_r($tasks);Code language: HTML, XML (xml)

In this example, we use the spaceship operator ( ), which has been available since PHP 7, to compare the time spent for each task and sort the tasks by hours.

Array ( [0] => Array ( [0] => Do excercise [1] => 1 ) [1] => Array ( [0] => Learn PHP programming [1] => 2 ) [2] => Array ( [0] => Practice PHP [1] => 2 ) [3] => Array ( [0] => Work [1] => 8 ) )Code language: PHP (php)

Summary

Источник

PHP Multidimensional Arrays

In the previous pages, we have described arrays that are a single list of key/value pairs.

However, sometimes you want to store values with more than one key. For this, we have multidimensional arrays.

PHP — Multidimensional Arrays

A multidimensional array is an array containing one or more arrays.

PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.

The dimension of an array indicates the number of indices you need to select an element.

  • For a two-dimensional array you need two indices to select an element
  • For a three-dimensional array you need three indices to select an element

PHP — Two-dimensional Arrays

A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).

First, take a look at the following table:

Name Stock Sold
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15

We can store the data from the table above in a two-dimensional array, like this:

$cars = array (
array(«Volvo»,22,18),
array(«BMW»,15,13),
array(«Saab»,5,2),
array(«Land Rover»,17,15)
);

Now the two-dimensional $cars array contains four arrays, and it has two indices: row and column.

To get access to the elements of the $cars array we must point to the two indices (row and column):

Example

We can also put a for loop inside another for loop to get the elements of the $cars array (we still have to point to the two indices):

Example

Complete PHP Array Reference

For a complete reference of all array functions, go to our complete PHP Array Reference.

The reference contains a brief description, and examples of use, for each function!

Источник

Multi dimensional array php

// Before php 5.4
$array = array(1,2,3);

// since php 5.4 , short syntax
$array = [1,2,3];

// I recommend using the short syntax if you have php version >= 5.4

Used to creating arrays like this in Perl?

Looks like we need the range() function in PHP:

$array = array_merge (array( ‘All’ ), range ( ‘A’ , ‘Z’ ));
?>

You don’t need to array_merge if it’s just one range:

There is another kind of array (php>= 5.3.0) produced by

$array = new SplFixedArray(5);

Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.

Supposing a large string-keyed array

$arr=[‘string1’=>$data1, ‘string2’=>$data2 etc. ]

when getting the keyed data with

php does *not* have to search through the array comparing each key string to the given key (‘string1’) one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it’s all hidden away.

However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :

Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It’s also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).

When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:

$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => 23 ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=0, is_ref=0)int 23

but :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => ’23’ ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=1, is_ref=0)string ’23’ (length=2)
or :

$arr = [‘bebe’ => ‘Bob’, ‘age’ => [1,2], ‘too’ => [1,2] ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
‘too’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2

This function makes (assoc.) array creation much easier:

function arr (. $array )< return $array ; >
?>

It allows for short syntax like:

$arr = arr ( x : 1 , y : 2 , z : 3 );
?>

Instead of:

$arr = [ «x» => 1 , «y» => 2 , «z» => 3 ];
// or
$arr2 = array( «x» => 1 , «y» => 2 , «z» => 3 );
?>

Sadly PHP 8.2 doesn’t support this named arguments in the «array» function/language construct.

Источник

Читайте также:  Как вывести случайное число php
Оцените статью