Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prefixing array keys with a string (:) in PHP

Tags:

arrays

php

key

Quick one; I know a solution, but I'm looking for something more elegant if it exists.

I'm using PDO for prepeared statements:

$sql = "INSERT INTO my_table (foo, bar, baz) VALUES (:foo, :bar, :baz)";

$source->execute($sql, array(
    ':foo' => $foo,
    ':bar' => $bar,
    ':baz' => $baz,
));

This is fine, but I want to pass in a previously created array, however the keys contained aren't prefixed by the colon (:), and I figure there must be an elegant way to take:

$array = array(
    'foo' => 'some',
    'bar' => 'random',
    'baz' => 'value',
);

And translate it into:

$array = array(
    ':foo' => 'some',
    ':bar' => 'random',
    ':baz' => 'value',
);

Without doing:

$temp = array();
foreach($array as $key => $value){
    $temp[':' . $key] = $value;
}
$array = $temp;

I've browsed the PHP docs, but I can't find a function (or sequence of) that suits the purpose.

Any ideas?


Addendum

Leaving the accepted answer, but +1 @chim for his clever 1-liner; solves the X in my XY problem. Reformatted solution:

$format = ':%s';
$values = array_flip(array_map(function ($key) use($format) {
    return sprintf($format, $key);
}, array_flip($values)));

Wrapped in a function, perhaps array_keys_format(array $array, $format)

like image 203
Dan Lugg Avatar asked Oct 01 '11 08:10

Dan Lugg


People also ask

Which is an array with string as an index in PHP?

PHP indexed array is an array which is represented by an index number by default. All elements of array are represented by an index number which starts from 0. PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as numeric array.

How get key of multidimensional array in PHP?

array_keys() returns the keys, numeric and string, from the array . If a search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.

Can an array have same key PHP?

No, you cannot have multiple of the same key in an associative array. You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key.

How do you access a key in an array?

Array elements can be accessed using the array[key] syntax. );


1 Answers

$source->execute($sql, array(
    'foo' => $foo,
    'bar' => $bar,
    'baz' => $baz
));

This is presuming the above calls PDOStatement::execute() under the hood, with the above array as its argument.1

:)


1) Tested with version 5.2.17 and 5.3.8 here, and working as expected.
like image 194
Decent Dabbler Avatar answered Oct 06 '22 00:10

Decent Dabbler