Accessing array elements in php

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.

Источник

Accessing array elements in 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.

Источник

Читайте также:  Data index number html
Оцените статью