According to the manual , the associative arrays PHP are "ordered maps". There are a multitude of situations in which they may be useful.
Loops
The premise is not correct, you can use it in a seamless repeat structure:
$teste = array( 'banana' => 'fruta', 'alface' => 'verdura' );
foreach( $teste as $key => $value ) {
echo "$key é $value<br>\n";
}
DBs
There are numerous situations where using associative arrays makes life easier. One of them, for example, is in the return of a line from a DB.
It's much easier to understand code with $campos['nome']
, $campos['idade']
... than $campos[1]
, $campos[2]
...
In addition, if you use numeric indexes in this case, it creates an immense confusion in the code each time you add or remove a field from your original query .
In PHP especially, there are many functions to work with associative arrays , both working with key and value, as well as each of the parts separately.
JSON
Another use where associative arrays are key, is when you need to work with JSON.
Of course, this here:
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
It can be represented like this:
array( "phoneNumbers" =>
array(
array( "type" => "home", "number" => "212 555-1234" ),
array( "type" => "office", "number" => "646 555-4567" )
)
)
and vice versa. PHP already has native functions that convert one format to another.
Web Forms
Within the primary function for which it was designed, PHP naturally uses associative arrays to receive the HTML form data, and query string data, usually through the variables $_POST
and $_GET
, among others.
This here:
<input type="text" name="batatinha">
When it is received by PHP, it already becomes this:
$_POST['batatinha']
or in this, depending on the method:
$_GET['batatinha']
More practicality is even harder to imagine. This applies to many other situations, such as sending files, for example.
Imagine if we had to count how many fields the form has, to sequentially access this information.