Push array into associative array PHP?

Push array into associative array PHP?

There are two ways to insert values in an associative array.

First method.

First of all, there is no array push for associative arrays.

However, this code will do the same thing.

1
2
3
4
5
6
7
8
9
10
11
<?php
$array = array();
 
//this works exactly like array_push
$array["Name"] = "Cristi";
$array["Name2"] = "Monica";
 
foreach($array as $word => $val){
	echo $word . ' ' . $val.'<br>';
}
?>

You can loop adding arrays having different keys.

Our example will result into two array elements, Name and Name2, each having different values.

What is interesting is that you cannot have 2 elements with the same Key as in “Name”.
You can’t add something like:
$array[“Name”] = “Joana”;
$array[“Name”] = “Ana”;

Because $array[“Name”] already exists.

If you want to add values with the same key, use method number 2.

Method 2.

We can use multidimensional arrays. It might sound hard to do, but in fact it is even easier than using the previous method.

Use this code:

2
3
4
5
6
7
8
9
10
11
<?php
$array = array();
 
array_push($array, array("Name", "Cristi"));
array_push($array, array("Name", "Monica"));
 
foreach($array as $word){
	echo $word[0] .'-'. $word[1] .'<br>';
}
?>

As you see, we are using the old array_push, but we are inserting an array inside an array.

And we echo it in a foreach, with $word[0] and $word[1];

Add a comment: