• 14
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Php: Concatenate string into all array items

I have this PHP snippet:

<?php
  $colors = array('red','green','blue');
  foreach ($colors as &$item)
  {
    $item = 'color-'.$item;
  }
  print_r($colors);
?>  

Output:

Array
(
  [0] => color-red
  [1] => color-green
  [2] => color-blue
)

Is it simpler solution ?

(some array php function like that array_insert_before_all_items($colors,"color-"))?

Thanks

The method array_walk will let you 'visit' each item in the array with a callback. With php 5.3 you can even use anonymous functions

Pre PHP 5.3 version:

function carPrefix(&$value,$key) {
  $value="car-$value";
}
array_walk($colors,"carPrefix");
print_r($colors);

Newer anonymous function version:

array_walk($colors, function (&$value, $key) {
   $value="car-$value";
});
print_r($colors);
  • 13
Reply Report

For older versions of php this should work

foreach ($colors as $key => $value) {
$colors[$key] = 'car-'.$value; //concatinate your existing array with new one
}
print_r($sbosId);

Result :

Array
(
[0] => car-red
[1] => car-green
[2] => car-blue
)
  • 2
Reply Report

Try this:

$colors = array('red','green','blue');

function prefix_car( &$item ) {
    $item = "car-{$item}";
}

array_walk( $colors, 'prefix_car');

It should work the same way you're doing it, albeit somewhat more sternly; array_walk gives an inkling more flexibility than manually looping.

  • 1
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions