0

Say I have an array like this:

$result=array("1", "2", "34");

And I have another array:

 $keys=array("id", "price", "day");

As it is, $result has numeric keys for each of its values. I want to add to those values associative keys, using the values in $keys as such, but without deleting the numeric keys. That is, I want the result to be:

array(6)
{ [0]=> string(1) "1"
  [1]=> string(1) "2"
  [2]=> string(2) "34"
  ["id"]=> string(1) "1"
  ["price"]=> string(1) "2"
  ["day"]=> string(2) "34"
}

I know that I could write a itty-bitty function to do this by hand, but is there any built-in function, among the myriad ones in PHP, to do this automatically? (My PHP knowledge is a bit rusty).

PaulJ
  • 1,646
  • 5
  • 33
  • 52
  • 2
    Use [array_combine()](http://www.php.net/manual/en/function.array-combine.php) - `$result = array_merge($result, array_combine($keys, $result));` though I don't understand why you need both enumerated and associative keys – Mark Baker Mar 10 '15 at 15:13
  • But array_combine() doesn't save the numeric keys. It creates a new assoc. array with only the associative keys. – PaulJ Mar 10 '15 at 15:14
  • That's why he make an `array_merge` after the `array_combine`. – magon Mar 10 '15 at 15:16
  • Aaahhh... with `array_merge` it's something different. That works. – PaulJ Mar 10 '15 at 15:18
  • @PaulJ - you must mean mysqli_fetch_array(), not mysqli_fetch_assoc(), the first returns both numeric and associative array. – n-dru Mar 10 '15 at 15:26
  • @n-dru: yes, that's what I meant. I've edited my post. – PaulJ Mar 10 '15 at 15:26

1 Answers1

1

You can do it like this:

$result=array("1", "2", "34");
$keys = array("id", "price", "day");
$array = $result + array_combine($keys, $result);

If you considered using array_merge, I recommend this thread: Array_merge versus +

Community
  • 1
  • 1
n-dru
  • 9,285
  • 2
  • 29
  • 42