skip to Main Content

I need to create an array like this:

['A1','A2','A3','A4','B1','B2','B3','B4','C1','C2','C3','C4'];

In php you can do this:

$letters = ['A', 'B', 'C'];
$arr = [];
foreach($letters as $l){
    for($i=1;$i<=4;$i++){
        $str = $l . '' . $i;
        array_push($arr, $str);
    }
}

Isn’t there a cleaner way to do this?

3

Answers


  1. Sure, array_push is pretty old school 😛 This is cleaner.

    $letters = ['A', 'B', 'C'];
    $arr = [];
    
    foreach($letters as $l){
        for($i = 1; $i <= 4; $i++){
            $arr[] = $l . $i;
        }
    }
    
    print_r($arr);
    
    Login or Signup to reply.
  2. It is not much cleaner, but I could come up with this:

    $arr = [];
    
    foreach ($letters as $letter) {
        for ($i = 1; $i <= 4; $i++) {
            $arr[] = "{$letter}{$i}";
        }
    }
    
    Login or Signup to reply.
  3. For sure! To avoid pushing elements in a mutable array, you could do this :

    $letters = ['A', 'B', 'C'];
    
    $arr = array_merge(
        ...array_map(
            function(string $letter): array {
                return array_map(
                    fn(string $v, int $k): string => $v . $k + 1,
                    array_fill(0, 4, $letter),
                    array_keys(array_fill(0, 4, null))
                );
            },
            $letters
        )
    );
    

    See ? So functional, so elegant.

    No, your way is better. Maybe get rid of the unneeded $str variable, but otherwise it’s about as readable as it could be.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search