Associative Array

<html> <body> <?php
/* First method to associate create array. */
[b]         \$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);[/b]

echo "Salary of mohammad is ". \$salaries['mohammad'] . "<br />";
echo "Salary of qadir is ".  \$salaries['qadir']. "<br />";
echo "Salary of zara is ".  \$salaries['zara']. "<br />";

/* Second method to create array. */
\$salaries['zara'] = "low";

echo "Salary of mohammad is ". \$salaries['mohammad'] . "<br />";
echo "Salary of qadir is ".  \$salaries['qadir']. "<br />";
echo "Salary of zara is ".  \$salaries['zara']. "<br />";
?> </body> </html>

Numerical Array

<?php
/* First method to create array. */
\$numbers = array( one, two, three, four, five);

foreach( \$numbers as \$value ) {
echo "Value is \$value <br />";
}

/* Second method to create array. */
\$numbers[0] = "one";
\$numbers[1] = "two";
\$numbers[2] = "three";
\$numbers[3] = "four";
\$numbers[4] = "five";

foreach( \$numbers as \$value ) {
echo "Value is \$value <br />";
}
?> </body> </html>

Look at both code's bold parts on how each different type of arrays create an array.

The Associative Array:
/* First method to associate create array. */
\$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);

The Numerical Array:
/* First method to create array. */
\$numbers = array( 1, 2, 3, 4, 5);

Why one uses "=>" and one not ? Are they not both procedural style ?
Look:
https://www.tutorialspoint.com/php/php_arrays.htm

## All 3 Replies

Arrays are assigned a numerical key automatically unless you override the key with your own custom name. When you're using the => you're assiging names to the keys instead of using the default numerical keys ( key => value ).

You could still use the => for both, i.e.
array ( 0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5);

Is the same as
array(1,2,3,4,5)

You end up with the exact same array, but why duplicate the work when PHP does it automatically for you. Less chance of an error

Also, you can declare a "starting index" with the following:

\$r = array(5=>"Ceredigion","Carmarthenshire","Llanelli",...);

These will have indexes 5,6,7, so as GP says, take advantage of PHP's automation. This obviously can't happen with associated arrays.

Also you can create array:

<?php
\$numbers[] = "one";
\$numbers[] = "two";
\$numbers[] = "three";
\$numbers[] = "four";
\$numbers[] = "five";
?>

it works same as:

<?php
\$numbers[0] = "one";
\$numbers[1] = "two";
\$numbers[2] = "three";
\$numbers[3] = "four";
\$numbers[4] = "five";
?>

... and another method to create array to give the same result:

<?php
\$numbers = ["one","two","three","four","five"];
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.