1

I have an array like this:

 $arr = array(
        "Posts" => "post", 
        "Projects" => "project"
 );

I want to add new element "News" => "new" to $arr on top with the same format, I have tried with below

 $new_element = array("News" => "new");
 array_unshift($arr, $new_element);

but I got

     Array ( 
       [0] => Array ( [News] => news ) 
       [Posts] => post
       [Projects] => project 
    )

They don't have the same format, please give advice. Thank you very much.

Arun Kumaresh
  • 6,211
  • 6
  • 32
  • 50
Yoona
  • 49
  • 6

6 Answers6

4

Try this..

$arr = array(
        "Posts" => "post", 
        "Projects" => "project"
 );

$new_element = array("News" => "new");

$arr = $new_element + $arr;
print_r($arr);

Output:

Array
(
    [News] => new
    [Posts] => post
    [Projects] => project
)
3

You can add it by:

$arr['News'] = "new";

Then sort your array keys.

ksort($arr);
simple guy
  • 633
  • 1
  • 6
  • 19
2

You can use array_merge:

$arr = array(
    "Posts"    => "post",
    "Projects" => "project"
);

$new_element = array("News" => "new");

$arr = array_merge($arr, $new_element);

Output:

Array
(
    [Posts] => post
    [Projects] => project
    [News] => new
)

Note: But be aware that when your source array has the same key, it will be replaced.

Thamilhan
  • 13,040
  • 5
  • 37
  • 59
2

You may use array_merge
if you want to add it at first try this:

$new_arr = array_merge(array("News" => "new"),  $arr);

if you want to add it at last try this:

$new_arr = array_merge($arr, array("News" => "new"));
B.Mossavari
  • 127
  • 6
0
$arr = array(
    "Posts" => "post", 
    "Projects" => "project"
);
$arr["News"] = 'new';
print_r($arr);
ryantxr
  • 4,119
  • 1
  • 11
  • 25
0
$arr = array(
        "Posts" => "post", 
        "Projects" => "project"
 );

$new_element = array("News" => "new");


$someArray=$new_element+$arr;


print_r($someArray);

using + we can insert key value pair array in the top of the existing array

Anitha S
  • 27
  • 3