I would like to know if there is a way to convert two Array keys into one Array key?
As an example the Array would look like:
[0] => '12345'
[1] => 'New'
[2] => 'York'
how can I combine [1] => 'New'
and [2] => 'York'
into [1] => 'New York'
?
All I was found is array_merge
that combines two Arrays. Even on how to concaternate two Array keys I could not find anything.
Thanks alot.
You can try :
$data = array(12345,"New","York");
echo concat($data, array(1,2)); //New York
//or
$data = array(12345,"New","York");
print_r(concatArray($data, array(1,2)));
Output
Array
(
[0] => 12345
[1] => New York
)
Function Used
function concat($array, $keys , $glue = " ") {
$values = array_intersect_key($array, array_flip($keys));
return implode($glue, $values);
}
function concatArray($array, $keys, $glue = " ") {
$last = null;
foreach ( $array as $key => &$value ) {
if (in_array($key, $keys)) {
if ($last === null) {
$last = $key;
continue;
}
$array[$last] .= $glue . $value;
unset($array[$key]);
}
}
return $array;
}
Here's a hint ;)
$new = $array[1] . ' ' . $array[2];
$array[1] = $new;
unset($array[2]);