0

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
print_r($data);

//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

4
  • I don't think str_replace will do what you want. Why don't u just do sth like this: $fields[':'.$key] = $field; unset $fields[$key]; Commented Aug 26, 2016 at 9:34
  • @LuciaAngermüller let me try this Commented Aug 26, 2016 at 9:35
  • str_replace(searchterm, replacement, subject), you're doing it wrong, probably ... also, you should create the empty array before the loop, not inside, or only the last entry will remain ... Commented Aug 26, 2016 at 9:36
  • Use the Version from Object Manipulator. It's an even cleaner Solution. Commented Aug 26, 2016 at 9:37

1 Answer 1

3

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank You it worked for me but I did not understood what actually you did here
okay so when ever we define an array like $a = array(); what ever we store in $a will be converted to array automatically
Thank you very much for the solutions and explanations
Actually, that syntax would mean we are declaring a new variable of type array. If a variable with a same name was already created earlier, they would be reset as a blank array. So, it's better to use this syntax for these kinds of operations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.