Generating an array with the same keys and values with PHP

Published on 2022-12-10 • Modified on 2022-12-10

This snippet shows how to generate an array with the same keys and values with PHP. This is the first time I have tried chatGPT to check my code, and it was wrong: I had to add more explanations so the answer is correct. The first answer is more concise. Let's continue and see what it can propose for the next ones. But the score is for now: COil 1 - ChatGPT 0 😁


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet234Trait
{
    public function snippet234(): void
    {
        // My answser
        $arr = array_combine($values = range(6, 11), $values);
        print_r($arr);

        // chatGPT question:
        // "Can you give me a PHP snippet to have an array with the same keys and values,
        //  the first value should be 6 and the last value should be 11".

        // chatGPT answer:
        //  - 1st try was wrong, I had to add to the question:
        // "Each key should be equal to the associated value"

        // Loop from 6 to 11 and add each value to the array
        $array = []; // added by me for PHPStan
        for ($i = 6; $i <= 11; ++$i) {
            $array[$i] = $i;
        }
        print_r($array);

        // winner = Me! 😁

        // That's it! 😁
    }
}

 Run this snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow   Read the doc  Random snippet

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @see Snippet234Trait
 */
final class Snippet234Test extends KernelTestCase
{
    /**
     * @see Snippet234Trait::snippet234
     */
    public function testSnippet234(): void
    {
        $myArr = array_combine($values = range(6, 11), $values);
        self::assertSame([
            6 => 6,
            7 => 7,
            8 => 8,
            9 => 9,
            10 => 10,
            11 => 11,
        ], $myArr);

        $chatGptArr = [];
        for ($i = 6; $i <= 11; ++$i) {
            $chatGptArr[$i] = $i;
        }

        self::assertSame($myArr, $chatGptArr);
    }
}