2

If I have this array: $array = ['1', '2', '3'];

I would like to replace all values in that array with asterisk sign *. Essentially, I want to get array like this: $new = ['*', '*', '*'];.

What is the best way to do this ? I am hoping that there is some short simple solution for this.

Thanks in advance.

6
  • array_fill() @ php.net Commented Jan 2, 2016 at 14:07
  • Seems a bit pointless to me, but array_walk($array, function(&$value) { $value = '*'; }); Commented Jan 2, 2016 at 14:08
  • 3
    But why not simply create an array of the same size using $new = array_fill(0, count($array), '*'); Commented Jan 2, 2016 at 14:09
  • I like this. But is it better than using array_map ? Commented Jan 2, 2016 at 14:14
  • 1
    @devlincarnate - Objects are pass by "pointer"; but scalars are always "pass by value", unless you specifically indicate "pass by reference" using & as described in the PHP Docs Commented Jan 2, 2016 at 14:22

1 Answer 1

1
<?php
$array = ['1', '2', '3'];
$newarray = array_map(function($val) { return "*"; }, $array);
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Still seems overkill compared to the array_fill(0, count($array), '*'); solution ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.