Is there Java HashMap equivalent in PHP?
In PHP, the equivalent to a Java HashMap would be an associative array. You can create one like this:
<?php
$map = array();
$map["key1"] = "value1";
$map["key2"] = "value2";
You can then access the values using the keys, like so:
<?php
$map = array();
$map["key1"] = "value1";
$map["key2"] = "value2";
echo $map["key1"]; // Outputs "value1"
Watch a video course
Learn object oriented PHP
You can also use the built-in array functions to manipulate the associative array, such as "foreach" loop
<?php
$map = array();
$map["key1"] = "value1";
$map["key2"] = "value2";
foreach($map as $key => $value){
echo $key . ' : ' . $value . PHP_EOL;
}
or "array_keys" for get all keys
<?php
$map = array();
$map["key1"] = "value1";
$map["key2"] = "value2";
$keys = array_keys($map);
print_r($keys);
Note that, in PHP, arrays are used to store multiple values and can be used as both lists and maps, unlike Java where arrays can only be used as lists.