Question

I am new to PHP. Sorry if this sounds simple.

I have this PHP associative array:

$X = array(
    'Model1' => '6',
    'Model2' => '5',
    'Model3' => '1'
);

I want to convert it to look like this:

$Y = array(
    'Model1' => 'prefix_Model1_postfix',
    'Model2' => 'prefix_Model2_postfix',
    'Model3' => 'prefix_Model3_postfix'
);

The value in each converted record is replaced with a prefix, then followed by the key, then followed by a postfix. How can this be done? Thank you very much. Is foreach a good start?

Was it helpful?

Solution

Yes, you can do it easily with foreach:

$arr = array("Model1" => 6, "Model2" => 5, "Model3" => 1);
$prefix = "prefix_";
$postfix = "_postfix";

foreach($arr as $key => $val){
$arr[$key] = $prefix.$key.$postfix;
}

print_r($arr);

DEMO

OTHER TIPS

you can also use array_walk:

array_walk($x, function($val,$key) use(&$x) { 
    $x[$key] = 'prefix_' . $key . '_postfix';
});

A different way to do with built-in function and closures:

<?php

$data = array(
  'Model1' => '6',
  'Model2' => '5',
  'Model3' => '1',
);

$data = array_map(function($data){
  return "prefix_Model{$data}_postfix";
}, $data);


var_dump($data);

?>

DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top