How to implement bulk add a fixed string before the value of PHP array using PHP built-in function

Source: Internet
Author: User
For example, the original array is

array('1','2','3','4');

The results I need to get

array('aaa1','aaa2','aaa3','aaa4');

How is the built-in function implemented?

Reply content:

For example, the original array is

array('1','2','3','4');

The results I need to get

array('aaa1','aaa2','aaa3','aaa4');

How is the built-in function implemented?

Array_walk () + Str_pad () can also be implemented:


  
   

输出结果为:

array(4) { [0]=> string(4) "aaa1" [1]=> string(4) "aaa2" [2]=> string(4) "aaa3" [3]=> string(4) "aaa4"}

http://ideone.com/nI0IgC

如果不使用闭包效率会更高,但 str_pad() 需要带多个参数,而 array_walk 只能传递一个参数,
所以目前只能这样了。

Well, there is no direct, but there can be a simple way of what the

 !--? php $arr = Array (' 1 ', ' 2 ', ' 3 ', ' 4 ');    $arr = Array_map (create_function (' $item ', ' return ' Aaa$item "; '), $arr); Print_r ($arr);? 
   -->  

     !--? php $a = array (1, 2, 3, 4);    Array_walk ($a, function (& $value, $key, $prefix) {$value = $prefix. $value;}, ' AAA '); Var_dump ($a);   

@ nice red Childe @Fwolf can see this version of my implementation, you can save the str_pad () , completely with Array_walk () implementation, Array_walk () The can not only pass a parameter, but also take a look at the manual.

PHP does not have such built-in functions.

Write a PHP version of yourself, it's not complicated.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.