According to the manual, the arrays PHP associatives are "ordered maps". There are a multitude of situations in which they can be useful.
Loops
The premise is not correct, you can use in a repetition structure without problems:
$teste = array( 'banana' => 'fruta', 'alface' => 'verdura' );
foreach( $teste as $key => $value ) {
echo "$key é $value<br>\n";
}
Dbs
There are numerous situations to use associative arrays makes life easier. One of them, for example, is in the return of a line of a DB.
It’s much easier for you to understand a code with $campos['nome']
, $campos['idade']
... than $campos[1]
, $campos[2]
...
Also, if you use numeric indexes in this case, it creates a huge confusion in the code every time you add or remove a field from your query original.
In PHP especially, there are many functions to work with associative arrays, both working with key and value, and each of the parts separately.
JSON
Another use in which associative arrays are fundamental, 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 overriding function for which it was designed, PHP naturally uses the arrays to receive data from HTML forms, and from query string, usually through the variables $_POST
and $_GET
, among others.
This here:
<input type="text" name="batatinha">
when received by PHP, it becomes that:
$_POST['batatinha']
or in this, depending on the method:
$_GET['batatinha']
More practicality is even more difficult to imagine. This applies to numerous other situations, such as uploading files, for example.
Imagine if we had to count how many fields the form has, to access this information sequentially.
Also known as hash.
– Guilherme Lautert