Sunday 15 July 2012

php - Combining array_keys and array_values to original array? -



php - Combining array_keys and array_values to original array? -

this question has reply here:

is elements order same after array beingness split array_keys() , array_values()? [duplicate] 1 reply

i have method inserts info table using associative array looks this:

array( "col1" => "value1", "col2" => "value2", "col3" => "value3", );

if utilize array_keys() , array_values() on array passed in can guarantee first item in each set, match original array passed in?

// note: validation excluded $keys = array_keys($data); // $data array passed in $values = array_values($data); $q = array_pad(array(), count($data), "?"); $this->query("insert `$this->table` (`" . implode("`,`", $keys) . "`) values (" . implode(",", $q) . ")", $values);

so, that, can guarantee $keys[1] , $values[1] same key , value original array, or possible col3 , value1?

another way it, if utilize array_combine($keys, $values) original array key => value pair (item order excluded)?

i worried if doesn't thinking value2 may go col3 instead of col2 or that....

yes, functions array_keys($data) , array_values($data) homecoming info in original order.

a search of php reference site combine_array() method show method combines arrays in original order well.

for example,

array( 'red' => 5, 'green' => 10, 'blue' => 15 );

would split keys array:

array( 'red', 'green', 'blue' );

and values array:

array( 5, 10, 15 );

combining these arrays array_combine($keys, $values) give array:

array( 'red' => 5, 'green' => 10, 'blue' => 15 );

examples php site

array keys php reference

<?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 illustration output:

array ( [0] => 0 [1] => color ) array ( [0] => color [1] => size )

array values php reference

<?php $array = array("size" => "xl", "color" => "gold"); print_r(array_values($array)); ?>

the above illustration output:

array ( [0] => xl [1] => gold )

array combine php reference

<?php $a = array('green', 'red', 'yellow'); $b = array('avocado', 'apple', 'banana'); $c = array_combine($a, $b); print_r($c); ?>

the above illustration output:

array ( [green] => avocado [red] => apple [yellow] => banana )

php arrays

No comments:

Post a Comment