Using an anonymous function with array_fill

So my goal is to create a string of random letters, and the letters can be repeated in a string. So I thought I could be smart and do this:

$str = implode(
  array_fill(0,10,
    function(){ 
      $c='abcdefghijklmnopqrstuvwxyz';
      return (string)$c{rand(0,strlen($c)-1)};
    }
  )
);
echo $str;

But I get the following error:

Crop fatal error: object of class Closure cannot be converted for a string to ...

This is literally the only thing in my script, so no, this is not something else. Now the manual describes the third argument for array_fill: "The value to populate," and it is indicated as accepting a mixed type. Now I know that “mixed” does not necessarily equate to “any” type, but it seems reasonable to me that I should use an anonymous function as the third argument if it returns a string, right? But apparently, I can’t do this.

, , ; , , , . , , "" , "" , php ( ), , , - - ?

+3
2

, .

:

// Declare the callback
$something = function(){ 
  $c='abcdefghijklmnopqrstuvwxyz';
  return (string)$c{rand(0,strlen($c)-1)};
}

, , , Closure.

// Fill the array
$list = array_fill(0,10,$something);

10 $something. 10 Closure. PHP , , .

// Join up the items in the array to make a string
$str = implode($list);

implode() , , , . __toString() ( " " ), Closure . .

, , , , PHP , , .


, array_map ; $something :

// Create 10 items, with nothing interesting in them
$list_of_nulls = array_fill(0, 10, null);

// Run the callback for each item of that list
// It will be given the current value each time, but ignore it
$list = array_map($something, $list_of_nulls);

// Now you have the list you wanted to join up
$str = implode($list);

, 10 :

$str = '';
for ( $i=0; $i<10; $i++ ) {
    $str .= $something();
}
+3

array_fill array_map:

$number_of_items = 25;

$array = array_map(function() {
  // Your callback here
  return 'foo';
}, array_fill(0, $number_of_items, null));
0

All Articles