PHP: Adding prefix strings to array values

后端 未结 4 1313
半阙折子戏
半阙折子戏 2020-12-10 10:59

What is the best way to add a specific value or values to an array? Kinda hard to explain, but this should help:



        
相关标签:
4条回答
  • 2020-12-10 11:38

    In the case that you're using a PHP version >= 5.3:

    $array = array('a', 'b', 'c');
    array_walk($array, function(&$value, $key) { $value .= 'd'; } );
    
    0 讨论(0)
  • 2020-12-10 11:42

    Use array_walk. In PHP 5.3 you can use an anonymous to define that callback. Because you want to modify the actual array, you have to specify the first parameter of the callback as pass-by-reference.

    0 讨论(0)
  • 2020-12-10 11:50

    Below code will add "prefix_" as a prefix to each element value:

    $myarray = array("test", "test2", "test3");    
    $prefixed_array = preg_filter('/^/', 'prefix_', $myarray);
    

    Output will be:

    Array ( [0] => prefix_test [1] => prefix_test2 [2] => prefix_test3 ) 
    
    0 讨论(0)
  • 2020-12-10 11:56

    Use array_map()

    $array = array('a', 'b', 'c');
    $array = array_map(function($value) { return ' '.$value; }, $array);
    
    0 讨论(0)
提交回复
热议问题