Création d'un tableau à deux dimensions avec PHP

Publié le 30/12/2021 • Actualisé le 30/12/2021


English language detected! 🇬🇧

  We noticed that your browser is using English. Do you want to read this post in this language?

Read the english version 🇬🇧 Close

Dans ce bout de code, nous voyons comment créer un tableau à deux dimensions avec PHP. Bien sûr, on peut faire des boucles avec la fonction range(), mais ici l'on utilise une seule ligne grâce à la fonction array_fill(). Dans ce cas, on a un "carré", si vous voulez une autre tailles, le premier arugument count représente la hauteur, alors que le deuxième représente la largeur du tableau voulu. Ce snippet trouvé dans la documentation de PHP date d'il y a 17 ans au moment où j'écris ces lignes !


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * J'utilise un trait PHP afin d'isoler chaque snippet dans un fichier.
 * Ce code doit être apellé d'un contrôleur Symfony étendant AbstractController (depuis Symfony 4.2)
 * ou Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Les services sont injectés dans le constructeur du contrôleur principal.
 */
trait Snippet181Trait
{
    public function snippet181(): void
    {
        $array = array_fill(1, 4, array_fill(1, 4, ''));
        var_dump($array);

        // That's it! 😁
    }
}

 Exécuter le snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  Plus sur Stackoverflow   Lire la doc  Snippet aléatoire

  Travaillez avec moi !

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @see Snippet181Trait
 */
final class Snippet181Test extends KernelTestCase
{
    /**
     * @see Snippet181Trait::snippet181
     */
    public function testSnippet181(): void
    {
        $array = array_fill(1, 4, array_fill(1, 4, ''));
        self::assertCount(4, $array);
        self::assertCount(4, $array[1]);
        self::assertCount(4, $array[2]);
        self::assertCount(4, $array[3]);
        self::assertCount(4, $array[4]);
    }
}