php array

An array in php is a variable that stores a set or sequence of values. One array can have many elements, and each element can hold a single value, such as text or numbers, or another array. An array containing other arrays is known as a multidimensional array

PHP supports arrays with both numerical and string indexes

Numerically indexed Arrays

Numerically indexed arrays are supported in most programming languages. In PHP, the indices start at zero by default

Initializing Numerically indexed arrays

$products = array( ‘Tires’, ‘Oil’, ‘Spark Plugs’ );

$products = [‘Tires’, ‘Oil’, ‘Spark Plugs’];

Accessing Array Element

To access the contents of a variable, you use its name. If the variable is an array, you access the contents using both the variable name and a key or index. The key or index indicates which of the values in the array you access. The index is placed in square brackets after the name. In other words, you can use $products[0], $products[1], and $products[2] to access each of the contents of the $products array

Access using loop

using for loop

for ($i = 0; $i<3; $i++) {
 echo $products[$i]." ";
}

using foreach loop

The foreach loop has a slightly different structure when using non-numerically indexed arrays

foreach ($prices as $key => $value) {
 echo $key." – ".$value."<br />";
}

The following code lists the contents of the $prices array using the each() construct:

while ($element = each($prices)) {
 echo $element['key']." – ". $element['value'];
 echo "<br />";
}

Array Operators

OperatorNameExampleResult
+Union$a + $bUnion of $a and $b. The array $b is appended to
$a, but any key clashes are not added
==Equality$a == $bTrue if $a and $b contain the same elements
===Identity$a === $bTrue if $a and $b contain the same elements, with
the same types, in the same order.
!=Inequality$a != $bTrue if $a and $b do not contain the same
elements.
<>Inequality$a <> $bSame as !=.
!==Non-identity$a !== $bTrue if $a and $b do not contain the same
elements, with the same types, in the same order
Array Operators

Leave a Comment