danul
danul

Reputation: 41

PHP change array values to create new array

this way how i get array from db:

$sql = "SELECT * FROM table_name";
$query = mysqli_query($conn, $sql);

$db_array = array();
// start fetch for words
if (mysqli_num_rows($query) > 0){
    while ($row = mysqli_fetch_assoc($query)){
        $db_array[] = $row;
    }
}

My array looked like this:

Array
(
    [cat cute] => animal#cute animal
    [cat women] => film
)

How to add '{' and '}' to all values? I wish i can get new array like this:

Array
(
    [cat cute] => {animal#cute animal}
    [cat women] => {film}
)

It's hard for me, i am new in php development.

Upvotes: 3

Views: 429

Answers (2)

Yury Fedorov
Yury Fedorov

Reputation: 14938

Since you want a new array, try this:

<?php
array_map(function($value)
{
    return '{' . $value . '}';
}, $arr);

array_walk() in rahul_m's answer modifies your array, while array_map() creates a new one.

Upvotes: 2

Rahul
Rahul

Reputation: 18567

Try this,

$arr =  array
(
    'cat cute' => 'animal#cute animal',
    'cat women' => 'film'
);
array_walk($arr, function(&$item){
   $item = '{'.$item.'}'; 
});
print_r($arr);

Here is the link for array_walk()

Upvotes: 3

Related Questions