简体   繁体   中英

PHP - Checking for empty element in 2D array

I have an array which looks like the following

array:2 [▼
  0 => array:1 [▼
    "input1" => "Something"
  ]
  1 => array:1 [▼
    "input2" => ""
  ]
]

Now the first element will always have some data. It is the second element I am interested in. At the moment, I am trying this

if(!empty($clientGroup[0][1]) || !empty($clientGroup[1][1]))
    var_dump("Some Data");
} else {
    var_dump("Both Empty");
}

The else should only be triggered if both elements are empty eg

array:2 [▼
  0 => array:1 [▼
    "input1" => ""
  ]
  1 => array:1 [▼
    "input2" => ""
  ]
]

If one of them have any data, the if should be triggered (so for the first array I showed, the if should be triggered).

How would I go about doing this, empty does not seem to work.

Thanks

The 2nd level keys do not exist so you will always be told the values are empty. Change the line

if(!empty($clientGroup[0][1]) || !empty($clientGroup[1][1]))

to,

if(!empty($clientGroup[0]['input1']) || !empty($clientGroup[1]['input2']))

and you should get the results you're after.

It's not realy 2D array because you have associative array inside an other array.

you must use key name (input1, input2) to access the value.

I recommend to use

if($retourdata[0]["input1"] !== "" || $retourdata[1]["input2"] !== "")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM