NiLL
NiLL

Reputation: 13843

How put same element on a first place in associative array, using a php?

I've a assoc array like array("id"=>"1","name"=>"NiLL"); and I need to add first element in this array. My finally array must be this array("error" => "0", "id"=>"1","name"=>"NiLL"); How I can do this, with out overwrite array?

Upvotes: 1

Views: 935

Answers (2)

Tadeck
Tadeck

Reputation: 137360

Just use documentation:

function array_unshift_assoc(&$arr, $key, $val) 
{ 
    $arr = array_reverse($arr, true); 
    $arr[$key] = $val; 
    $arr = array_reverse($arr, true); 
    return count($arr); 
}

In this case:

$your_array = array("id"=>"1","name"=>"NiLL");
array_unshift_assoc($your_array, 'error', '0');

Upvotes: 3

Sampson
Sampson

Reputation: 268354

You could use array_merge():

array_merge( array("Error" => 0), $other_array );

Your first parameter will be an array with the key/value you wish to insert into your other array.

Upvotes: 2

Related Questions