9951 explained code solutions for 126 technologies


php-fakerHow can I generate a PHP Faker array?


Generating a PHP Faker array can be done using the Faker library. Faker is a PHP library that generates fake data for you. To generate a PHP Faker array, you can use the following example code:

<?php

require_once 'vendor/autoload.php';

$faker = Faker\Factory::create();
$array = [];

for ($i=0; $i < 10; $i++) {
    $array[] = [
        'name' => $faker->name,
        'address' => $faker->address,
        'text' => $faker->text,
    ];
}

print_r($array);

Output example

Array
(
    [0] => Array
        (
            [name] => Dr. Terence Doyle
            [address] => 8063 Schimmel Stravenue
Lake Jaida, NJ 81043
            [text] => Qui quisquam voluptatem consequuntur quia.
        )

    [1] => Array
        (
            [name] => Dr. Elton Schaden
            [address] => 441 Reinger Divide
East Lue, WA 45902
            [text] => Quia voluptatem officiis et et nisi.
        )

    [2] => Array
        (
            [name] => Prof. Aylin Schuster
            [address] => 47859 Toy Fields
New Hans, VA 57900
            [text] => Iusto voluptatem quo et voluptatem.
        )

    ...
)

The code above will generate an array of 10 elements, each element containing 3 values (name, address, and text).

The code consists of the following parts:

  1. require_once 'vendor/autoload.php'; - This loads the Faker library.
  2. $faker = Faker\Factory::create(); - This creates a Faker instance.
  3. $array = []; - This creates an empty array.
  4. for ($i=0; $i < 10; $i++) { - This starts a loop that will run 10 times.
  5. $array[] = [ - This adds a new element to the array.
  6. 'name' => $faker->name, - This adds a 'name' key to the element, with a value generated by the Faker instance.
  7. 'address' => $faker->address, - This adds an 'address' key to the element, with a value generated by the Faker instance.
  8. 'text' => $faker->text, - This adds a 'text' key to the element, with a value generated by the Faker instance.
  9. ]; - This closes the element.
  10. print_r($array); - This prints the array.

For more information, please refer to the Faker documentation.

Edit this code on GitHub