-1

I have an array

$a = array('a', 'b', 'c');

What is the shortest and optimum way to change it to

$a = array('1a1', '1b1', '1c1');
johnlemon
  • 20,761
  • 42
  • 119
  • 178

6 Answers6

7
$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);
KingCrunch
  • 128,817
  • 21
  • 151
  • 173
2

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);
Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
  • This is too long, use KingCrunch's solution – Andreas Wong Jul 27 '11 at 08:55
  • You shouldn't use `count()` within the `for`-test-expression, even if its only an example. – KingCrunch Jul 27 '11 at 09:04
  • Thanks :) Its just, because beginner may read it over and over again (here and in other communities) and may come to the conclusion, that there is nothing wrong with it. – KingCrunch Jul 27 '11 at 09:09
  • @kingCrunch , you are correct in suggesting not using functions in for loop to avoid call at each time, but count is O(1) and has not effect on efficiency : http://stackoverflow.com/questions/4566314/php-what-is-the-complexity-i-e-o1-on-of-the-function-count – DhruvPathak Jul 27 '11 at 09:12
  • Its a function, that is called in every iteration. You are right with `O(1)`, but there is a linear factor (compared to the variable) `T($cnt) < T(count($a))`, or better `T($cnt) = T(count($a)) * constant`. – KingCrunch Jul 27 '11 at 09:19
2
function add1s($val) {
  return '1' . $val . '1';
}

$a = array_map("add1s", $a);
Dan Grossman
  • 51,866
  • 10
  • 112
  • 101
0

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);

?>
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
  • As mentioned at andreas' answer: You shouldn't use `count()` within the `for`-test-expression even if its just an example, because others can come to the conclusion, that this may be a good idea. – KingCrunch Jul 27 '11 at 09:08
0
foreach($a as $key => $val) {
  $a[$key] = '1' . $val . '1';
}
KingCrunch
  • 128,817
  • 21
  • 151
  • 173
0
$a = array('a', 'b', 'c');
$a = array_map(function ($x) { return ("1".$x."1"); }, $a);
print_r($a);
Xupypr MV
  • 935
  • 10
  • 18