Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

php - when am trying to upload excel sheet it will uploaded successfully but am getting an error undefined offset: 500 in line 159

When I upload an excel sheet it will uploaded successfully but I'm getting an error:

undefined offset: 500 in line 159

    $data = $rows[0];
   
    if(!empty($data) && count($data)){
        foreach ($data as $key => $value) {
            if(!empty($value) && $key != 0 && $value[0]){
                
                $product['description'] = $value[500]; //this line causing error undefined offset:500
                
question from:https://stackoverflow.com/questions/65871587/when-am-trying-to-upload-excel-sheet-it-will-uploaded-successfully-but-am-gettin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Method: 1

use array_key_exists() & check using ternary.

$product['description'] = array_key_exists($value[500]) ? $value[500] : default value" ;
  • Disadvantage: array_key_exists() will iterate over the whole array thus has more time complexity.

Method: 2

use Null coalescing

$product['description'] = $value[500] ?? "default value";

(Null coalescing is introduced in PHP 7)
or

$product['description'] = isset($value[500]) ? $value[500] : "default value";

both will do the same work, just checks for the value for null, but will also return false if the key exists but value in it is null.(you can use !empty() for that.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...