I'm trying to implode an array of both its keys and values. I can easily get the keys with the implode, but find I have to repeat myself for the keys.
Currently I am doing this:
$values = array(
'id' => $sel['id'],
'creator_id' => $sel['creator_id'],
'campaign_id' => $sel['campaign_id'],
'save_results' => $sel['save_results'],
'send_results_url' => $sel['send_results_url'],
'reply_txt' => $sel['reply_txt'],
'allow_multiple_votes' => $sel['allow_multiple_votes']
);
$cols = '';
$vals = '';
$first = true;
foreach($values as $col => $val) {
if(!$first) {
$cols .= ', ';
$vals .= ', ';
}
$cols .= $col;
$vals .= $val;
$first = false;
}
The part that bothers me is this:
foreach($values as $col => $val) {
if(!$first) {
$cols .= ', ';
$vals .= ', ';
}
$cols .= $col;
$vals .= $val;
$first = false;
}
Is there a way to implode the array keys?
For example, I could do
$vals = implode(', ', $values);
to implode the values, but I need to do this as well for the keys.
I could also use
$keys = array();
foreach($values as $col => $val)
$keys[] = $col;
$cols = implode(', ', $keys);
$rows = implode(', ', $values);
but it still requires me to loop over it creating another array, surely there is a better way, do just get the keys?
$array = ['a very' => ['complex' => 'array']]; $imploded = var_export($array, true); This will return the exported var instead of directly printing it on the screen and the var $imploded will contain the full export.
The explode() function breaks a string into an array, but the implode function returns a string from the elements of an array.
Definition and Usage The implode() function returns a string from the elements of an array. Note: The implode() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments. Note: The separator parameter of implode() is optional.
The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.
$cols = implode(', ',array_keys($values));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With