Home > Enterprise >  Array_Push in php always add last value
Array_Push in php always add last value

Time:10-09

Everyone

I'm having a problem using array of object and faker in laravel.

I tried to make a series of fake data using faker to pass into a table using array, but my array value keep repeating the same one even though I already used a for loop and faker.

Your answer mean a lot to me. Thanks in advance.

Here's My Controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Faker\Factory as Faker;

class bio{
    public $nama;
    public $alamat;
    public $no;
    public $email;
}

class PegawaiCTRL extends Controller{
    public function faking(){
        
        $faker = Faker::create();
        $data  = new bio;
        $bio   = [];

        for ($i = 0; $i < 100; $i  ){
            $data->nama     = $faker->unique()->name('Male');
            $data->alamat   = $faker->unique()->address();
            $data->no       = $faker->unique()->phoneNumber();
            $data->email    = $faker->unique()->email();
            array_push($bio, $data);
        }
    
        return $bio;
        //return View('v_IPegawai', ['datas' => $bio]);
    }
}

The Output

CodePudding user response:

You edit the same object every time, hence it gets updated with new values. Instead, create a new object every time in the loop like below:

$faker = Faker::create();
$bio   = [];

for ($i = 0; $i < 100; $i  ){
    $data  = new bio;
    $data->nama     = $faker->unique()->name('Male');
    $data->alamat   = $faker->unique()->address();
    $data->no       = $faker->unique()->phoneNumber();
    $data->email    = $faker->unique()->email();
    array_push($bio, $data);
}

Note: Please follow PSR-Standards for Class Names. bio should be Bio.

  • Related