1

my array is

$hello= array( Code => 'TIR', Description => 'Tires', Price => 100 )

now i want to add a value in array beginning of an array not the end of an array.... and results i want is

$hello= array( ref=>'World', Code => 'TIR', Description => 'Tires', Price => 100 )

UPDATE

actually i need any value that is coming will be added in the beginning of an array....this is not single value.. ref=world.... this is coming from output...like if i add quantity=50, then it should be added beginning of an array before 'ref' an array should be

$hello= array(quantity=>'50', ref=>'World', Code => 'TIR', Description => 'Tires', Price => 100 )

Brad Werth
  • 16,308
  • 9
  • 57
  • 85
diEcho
  • 50,018
  • 37
  • 156
  • 230

4 Answers4

3

I would use array_merge()

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

$hello = array ("Code" => "Tir" .....); // you should really put quotes 
                                        // around the keys!
$world = array ("ref" => "World");

$merged = array_merge($world, $hello);
Pekka
  • 418,526
  • 129
  • 929
  • 1,058
2

You can use the + operator:

$hello = array( 'Code' => 'TIR', 'Description' => 'Tires', 'Price' => 100 );
$hello = array('ref' => 'World') + $hello;
print_r($hello);

would give

Array
(
    [ref] => World
    [Code] => TIR
    [Description] => Tires
    [Price] => 100
)

Like Pekka said, you should put quotes around the keys. The PHP manual explicitly states omitting quotes is wrong usage. You might also want to check out my answer about the difference between using the + operator vs using array_merge to decide which you want to use.

Community
  • 1
  • 1
Gordon
  • 296,205
  • 68
  • 508
  • 534
1
$a= array( 'a' => 'a' );
$b = array( 'b' => 'b' );

$res = $b + $a;
//result: ( 'b' => 'b', 'a' => 'a' )
Guillaume Massé
  • 7,057
  • 6
  • 37
  • 54
0

$hello = array_merge(array('ref'=>'World'), $hello);