I frequently need to turn a PHP array such as:
$cols = array ( [access] => N [card] => N [child] => Y [cot] => Y [dinner] => N [ground] => Y [allyear] => Y [pets] => N [wifi] => Y )
// derived from 'print_r', I'm aware this is not how one would construct the array
into a string (part of a query string for MySQL):
$cols_new = "access = 'N', card = 'N', child = 'Y', cot = 'Y', dinner = 'N', ground = 'Y', allyear = 'Y', pets = 'N', wifi = 'Y'"
I’ve done it with a FOREACH loop, but I’m just curious to know if there’s a better way (e.g. an array function I’ve missed).
Implode just gives me a string of the values. “N, N, Y, Y, N, Y, Y, N, Y”. I’ve wondered about ‘Array_walk’ but even if it were to work there will be at least as many lines of code as with the FOREACH loop:
$cols_new = '';
foreach ($cols as $key => $value) {
$cols_new .= $key . " = '" . $value . "', ";
}
$cols_new = substr($cols_new, 0, -2); // remove trailing comma and space
I am using this procedure quite freqently, so if there’s a better/shorter way it could be handy when I come to anonymise it.
In short what I’m looking for is:
$cols_new = someExistingPHPFunction($cols);
Failing which I’ll have to write my own based on what I’ve done so far.