Mark Alan Mark Alan - 5 months ago 20
PHP Question

replacing array index value

I have an array in which there are users values are stored that will be sent to execute(); function for mysqli query.
So, I want the index values to be replaced.

Now what I have done here is used str_replace(); function to do so within foreach loop but the problem is that how I will get the updated array?

$fields = array(
'field_id' => '123',
'field_name' => 'test_name'

foreach ($fields as $key => $field) {
$val = str_replace($key, $key, ':'.$key);
$data = array();
$data[$val] = $field;

//I only got the value for the last index 1st is not there

//output which I am expecting will be the following
$fields = array(
':field_id' => '123',
':field_name' => 'test_name'

Please let me know if any one could help me out


The objective is to prepend each key with a colon (:).

This can be achieved by looping through the main array, modifying each key and filling these key value pairs in $newArray.

We can loop through $fields, fetch each key and prepend it with ':', and make this the key of our $newArray. i.e field_id becomes :field_id, field_name becomes :field_name.. and so on.

The values are copied from $fields and put in $newArray as it is.

$newArray = array();
foreach ($fields as $key => $field) {
     $newArray[':'.$key] = $field;