fbc's avatar
Level 2

How do you test if a variable is numeric or not?

I just finish creating a CSV upload function and am pretty happy with it, but feel it could be improved.. I would like to have it skip the header or basically any row where $data [5] is not numeric. I think a CONTINUE will do the trick, but I need to know how to test if a variable is numeric in value or not.

I used this code:

        if (($handle = fopen ( request()->file('file') , 'r' )) !== FALSE) {
            while ( ($data = fgetcsv ( $handle, 1000, ',' )) !== FALSE ) {
                $reading = new Utility_Meter_Readings ();
                $reading->property_id = $request->property_id;
                $reading->utility_id = $request->utility_id;
                $reading->resource_type = $request->resource_type;
//                if($data [5] ??) {
//                    continue;
//                }
                $date = date_create($data [3]);
                $reading->time = date_format($date, 'U');
                $reading->kwh = $data [5];
                $reading->save ();
            }
            fclose ( $handle );
        }

I got it here: https://justlaravel.com/import-csv-data-store-database/

It seems to be more corePHP than Laravel. So how do I test if a variable has a numeric value?

0 likes
6 replies
fbc's avatar
Level 2

@CRONIX - getting: "Undefined offset: 5" Error with this:

        if (($handle = fopen ( request()->file('file') , 'r' )) !== FALSE) {
            while ( ($data = fgetcsv ( $handle, 1000, ',' )) !== FALSE ) {
                $reading = new Utility_Meter_Readings ();
                $reading->property_id = $request->property_id;
                $reading->utility_id = $request->utility_id;
                $reading->resource_type = $request->resource_type;
                if(is_numeric($data [5])) {
                   //do nothing
                }
                else {
        //skip importing this record
        continue;
        }
                    $date = date_create($data [3]);
                $reading->time = date_format($date, 'U');
                $reading->kwh = $data [5];
                $reading->save ();
            }
            fclose ( $handle );
        }

wondering why $data [5] works fine outside of the if statement.

Cronix's avatar

That doesn't have anything to do with is_numeric itself, or testing if a number is numeric.

Which line is the error on? One or both of the 2 $data[5] elements doesn't exist.

fbc's avatar
Level 2

@CRONIX - yup you are correct.. I uploaded the wrong file.. sorry for the bother, and thank you very much for your help!!

fbc's avatar
Level 2

@CRONIX - I get the same error when trying to test for the existance of the variable. if (!$data[5]){ return view('errors.no-data'); } how would I do that without getting the error?

Please or to participate in this conversation.