Php map add key value

In this article let us understand what a “key” and a “value” is in an array is & also look at the different methods by which we can obtain these key-value pairs

Table of Contents

  • What are a key and value in an array?
  • Different methods to obtain key-value pairs
  • Browser Support

What are a key and value in an array?

Keys are indexes and values are elements of an associative array. Associative arrays are basically objects in JavaScript where indexes are replaced by user-defined keys. They do not have a length property like a normal array and cannot be traversed using a normal for loop

Here’s an example of an associative array

var arr = { "one": 1, "two": 2, "three": 3 }; 

Unlike simple arrays, we use curly braces instead of square brackets. The content or values of associative arrays is accessed by keys.

In the above array, one, two & three are keys, and 1, 2 & 3 are values. These can be obtained individually using the keys() & values() methods as shown below

//to get values
for (let value of Object.values(arr)) {
    alert(value);
}
//Output: 1, 2, 3

//to get keys
for (let value of Object.values(arr)) {
    alert(value);
}
//Output: one, two, three

Different methods to obtain key-value pairs

Now that we know how to get keys & values in an array, let us look at the different methods to obtain key-value pairs.

Let us first store the previously extracted keys & values in separate arrays

var keys = ["one", "two", "three"];
var values = [1, 2, 3];

Method 1: Using an object to store key => value pairs

In this method we store the elements from the “keys” array & the corresponding values from the “values” array using an associative array "obj"

// create object
var obj = {};

// Loop to insert key & value in this object one by one
for (var i = 0; i < keys.length; i++) {
    obj[keys[i]] = values[i];

} 

// output can be displayed as : one => 1  two => 2 three => 3

Method 2: Using the map() method

A map is a collection of elements where each element is stored as a key, value pair. The objects of map type can hold both objects and primitive values as either key or value. On traversing through the map object, it returns the key, value pair in the same order as inserted.

// Create a map object 
var map = new Map(); 
      
 // Loop to insert key & value in this object one by one
for(var i = 0; i < keys.length; i++){ 
    map.set(keys[i], values[i]); 
} 
// output can be displayed as : one => 1  two => 2 three => 3

Browser Support

The following are the lowest browser versions that fully support the following methods.

keys() method

Chrome: 38; Firefox: 28; Safari: 8; Opera: 25; Edge: 12

values() method

Chrome: 54; Firefox: 47; Safari: 41; Opera: 10.1; Edge: 14

map() method

Chrome: All versions; Firefox: 1.5; Safari: All versions; Opera: All versions; Edge: 9.0

We have given two arrays containing keys and values and the task is to store it as a single entity in the form key => value in JavaScript. In JavaScript, the array is a single variable that is used to store different elements. It is usually used once we need to store a list of parts and access them by one variable. We can store key => value array in JavaScript Object using methods discussed below: 

Method 1: In this method we will use Object to store key => value in JavaScript. Objects, in JavaScript, is the most important data-type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript’s primitive data-types(Number, String, Boolean, null, undefined and symbol). Objects are more complex and each object may contain any combination of these primitive data-types as well as reference data-types. 

Approach: We will traverse through the whole array and one by one add the keys from the keys (array) and the corresponding values from values (array) in the Object. 

Syntax:

for(var i = 0; i < keys.length; i++){
        // obj = Object
        // keys = key array
        // values = value array
        obj[keys[i]] = values[i];
}

Example: 

javascript

<script>

    var keys = [1, 2, 3];

    var values = ["GeeksforGeeks", "Computer", "Science"];

    var obj = {};

    for(var i = 0; i < keys.length; i++){

        obj[keys[i]] = values[i];

    }

    for (var key of Object.keys(obj)) {

        document.write(key + " => " + obj[key] + "</br>")

    }

</script>              

Output:

1 => GeeksforGeeks
2 => Computer
3 => Science

Method 2: In this method we will use Map to store key => value in JavaScript. The map is a collection of elements where each element is stored as a key, value pair. Map objects can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, value pair in the same order as inserted. 

Approach: We will traverse through the whole array and one by one add the keys from the keys (array) and the corresponding values from values (array) in the map. 

Syntax:

for(var i = 0; i < keys.length; i++){
        // mp = Map
        // keys = key array
        // values = value array
        map.set(keys[i], values[i];
}

Example: 

javascript

<script>

    var keys = [5, 2, 3, 6, 10];

    var values = ["Geeks", "for", "Geeks", "Course", "Algorithm"];

    var map = new Map();

    for(var i = 0; i < keys.length; i++){

        map.set(keys[i], values[i]);

    }

    for (var key of map.keys()) {

        document.write(key + " => " + map.get(key) + "</br>")

    }

</script>                   

Output:

5 => Geeks
2 => for
3 => Geeks
6 => Course
10 => Algorithm

Method 3: In this method we will use reduce to store key => value in JavaScript. The reduce is method which is use iterate over the list of elements. This method is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator.

Syntax:

array.reduce( function(total, currentValue, currentIndex, arr), initialValue )

Example: 

Javascript

<script>

    var keys = [5, 2, 3, 6, 10];

    var values = ["Geeks", "for", "Geeks", "Course", "Algorithm"];

    var ans = values.reduce(( acc, value, i ) => {

        acc[keys[i]] = value;

        return acc}, {})

    for (const key in ans) {

        console.log(`${key}  => ${ans[key]} ` )

    }

 </script>

Output:

2  => for 
3  => Geeks 
5  => Geeks 
6  => Course 
10  => Algorithm 

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.


How do you push a key and value in an array?

Answer: Use the Square Bracket [] Syntax php // Sample array $array = array("a" => "Apple", "b" => "Ball", "c" => "Cat"); // Adding key-value pairs to an array $array["d"] = "Dog"; $array["e"] = "Elephant"; print_r($array); ?>

How do you add a key to an array?

To add a key/value pair to all objects in an array: Use the Array. map() method to iterate over the array. On each iteration, use the spread syntax to add the key/value pair to the current object. The key/value pair will get added to all objects in the new array.

What is Array_push in PHP?

Definition and Usage. The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).

What is the use of Array_map in PHP?

The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.