Search code examples
phpcsvfgetcsv

Keep leading zeros in CSV data when using fgetcsv function in PHP


I am having some troubles finding a solution after researching for hours. I have one column of data called LAST4 in my database. Some data examples "0564", "0002", etc... When I run the script, it removes the leading zero of "0564" and turns it into "564" or "0002" results to "2". How can I save the data with the leading zeros? Any help would be appreciated!

    //CSV Database 
    $handle = fopen("/home/file/path.csv", "r");

    $count = 0;
    $members = array();

    while(($data = fgetcsv($handle, 10000, ",")) !== FALSE) {

      if ($count >= 1) { 

         /* Convert Date of Birth to Timestamp with Function */   
         $dateofbirth = date("Y-m-d", strtotime($data[2]));  

         /* Convert Layoff Date to Timestamp with Function */   
         $layoffdate = date("Y-m-d H:i:s", strtotime($data[5])); 


        /* Build Variables for User Access Account */
        $userlogin = $dateofbirth . '-' . $data[3];
        $userpw = $data[1] . '' . $data[3];
        $userem = $dateofbirth . '-' . $data[3] . '@example.org';

        /* Creates a New User For User Access */
         $userDatas[] = array(
          'user_login' => $userlogin,
          'first_name' => $data[0],
          'last_name' => $data[1],
          'user_pass' => $userpw,
          'user_email' => $userem,
          'user_url' => '',
          'role' => 'member'
         );

         /* Creates New Member Entry in Table */
         $members[] = array(  
         'FIRST_NAME' => $data[0],
         'LAST_NAME' => $data[1],
         'DOB' => $dateofbirth, 
         'LAST4' => $data[3],
         'FLAG' => $data[4],
         'LAID_OFF_DATE' => $layoffdate, 
         'PHONE_NUMBER' => $data[6]
         ); 

       }

       $count++;

Solution

  • Try casting it to string first. So instead of:

    'LAST4' => $data[3],
    

    You could use:

    'LAST4' => (string)$data[3],
    

    And similarly with other values you'd want it to happen with.