I have an array
$a = array('a', 'b', 'c');
What is the shortest and optimum way to change it to
开发者_C百科$a = array('1a1', '1b1', '1c1');
$a = array("1{$a[0]}1", "1{$a[1]}1", "1{$a[2]}1");
With a dynamic number of values you must use a loop
foreach ($a as &$value) $value = "1{$value}1";
(I know: Omitting the braces {}
is usually not "a good style", but in such simple cases there is nothing wrong with it. Of course you can add the braces again, if you don't feel comfortable with the compacted form).
or (with PHP5.3)
$a = array_map(function ($value) { return "1{$value}1"; }, $a);
function add1s($val) {
return '1' . $val . '1';
}
$a = array_map("add1s", $a);
most optimum is probably just a good ol' for loop
$cnt = count($a);
for($i = 0; $i < $cnt; $i++) {
$a[$i] = '1' . $a[$i] . '1';
}
or even lambda
$a = array_map(function($el) { return '1' . $el . '1'; }, $a);
$a = array('a', 'b', 'c');
$a = array_map(function ($x) { return ("1".$x."1"); }, $a);
print_r($a);
use a loop or array_map. Simple and clean and efficient .
Loop :
<?php
for($i = 0; $i < count($a); $i++) {
$a[$i] = '1'.$a[$i].'1';
}
var_dump($a);
?>
Array_map:
<?php
function sandwich($item)
{
return '1'.$item.'1';
};
$a = array('a', 'b', 'c');
$a = array_map("sandwich",$a); /* you can also use lambda functions for PHP >= 5.3.0
var_dump($a);
?>
foreach($a as $key => $val) {
$a[$key] = '1' . $val . '1';
}
精彩评论