Is there Java HashMap equivalent in PHP?
In PHP, the equivalent to a Java HashMap would be an associative array.
In PHP, the equivalent to a Java HashMap would be an associative array. You can create one like this:
Example of creating an associative array in PHP
<?php
$map = array();
$map["key1"] = "value1";
$map["key2"] = "value2";You can then access the values using the keys, like so:
Example of Java HashMap equivalent in PHP
<?php
$map = array();
$map["key1"] = "value1";
$map["key2"] = "value2";
echo $map["key1"]; // Outputs "value1"
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
You can also use the built-in array functions to manipulate the associative array, such as "foreach" loop
Example of using array functions to manipulate a associative array in PHP
<?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
Example of Java HashMap equivalent in PHP with using the built-in array functions
<?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.