This question already has an answer here:
I have a method that inserts data into a table using an associative array that looks like this:
array(
"col1" => "value1",
"col2" => "value2",
"col3" => "value3",
);
If I use array_keys()
and array_values()
on the array passed in can I guarantee that the first item in each set, match the original array passed in?
// Note: validation excluded
$keys = array_keys($data); // $data is the array passed in
$values = array_values($data);
$q = array_pad(array(), count($data), "?");
$this->query("insert into `$this->table` (`" . implode("`,`", $keys) . "`) values (" . implode(",", $q) . ")", $values);
So, with that, can I guarantee that $keys[1]
and $values[1]
are the same key and value from the original array, or is it possible that they could be col3
and value1
?
Another way to say it, if i use array_combine($keys, $values)
will I get the original array key => value
pair back (item order excluded)?
I am worried that if this doesn't do what I am thinking that value2
may go into col3
instead of col2
or something like that....
</div>
Yes, the functions array_keys($data)
and array_values($data)
will return the data in the original order.
A search of the PHP reference site for the array_combine()
method will show that the method combines the arrays in their original order as well.
For example,
array(
'red' => 5,
'green' => 10,
'blue' => 15
);
would be split into the keys array:
array(
'red',
'green',
'blue'
);
and the values array:
array(
5,
10,
15
);
Combining these arrays with array_combine($keys, $values) would give you the array:
array(
'red' => 5,
'green' => 10,
'blue' => 15
);
Examples from PHP site
<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
$array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
print_r(array_keys($array));
?>
The above example will output:
Array
(
[0] => 0
[1] => color
)
Array
(
[0] => color
[1] => size
)
<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>
The above example will output:
Array
(
[0] => XL
[1] => gold
)
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c);
?>
The above example will output:
Array
(
[green] => avocado
[red] => apple
[yellow] => banana
)
Using a foreach loop you will always be sure that the key/value pair matches. As other's have pointed out you should at least escape the input values and/or use PDO for insertion. I haven't included that below since that was not your actual question.
foreach($array as $k=>$v){
//add keys to key array
$keys[]=$k;
//add values to value array
$vals[]=$v;
}