Home > OS >  Trying to access an array in an object results in error - Undefined property: stdClass::$files
Trying to access an array in an object results in error - Undefined property: stdClass::$files

Time:03-17

I'm passing an object which contains an array as form input. When I try to access the array (and count the elements) I get the error Undefined property: stdClass::$files

When I var_dump the whole object I get this, which is expected:

object(stdClass)[29]
  public '6' => 
    object(stdClass)[28]
      public 'files' => 
        array (size=0)
          empty
      public 'packages' => 
        array (size=1)
          0 => string 'program_data/6/packages/1646756076.zip' (length=38)
      public 'scripts' => 
        array (size=1)
          0 => string 'program_data/6/scripts/MEER_munger.py' (length=37)

I'm trying to check if the files array is empty. In my code I have this:

foreach($selectedFiles as $key=>$d){
  var_dump($d->files);
  if (count($d->files)!==0) {                    
      mkdir($dir.'/files');
      foreach($d->files as $file) {
        $source = FCPATH.$file;
        $fileName = substr($file, strrpos($file, '/')   1);
        copy($source,$dir.'/files/'.$fileName);
      }
   }
}

the var_dump of $d->files shows me an empty array. So if it's an array, why is count($d->files) throwing an error?

Thank you for the help!

CodePudding user response:

Instead of:

if (count($d->files)!==0) { ... }

Try checking if the array is not empty.

if (!empty($d->files)) { ... }

PHP: empty - Manual

Extra Note:

Don't use isset here, since that only works to check if a variable is declared and not null.

PHP: isset - Manual

Comparison of empty() and isset(), copied from the PHP manual:

<?php
$var = 0;

// Evaluates to true because $var is empty
if (empty($var)) {
    echo '$var is either 0, empty, or not set at all';
}

// Evaluates as true because $var is set
if (isset($var)) {
    echo '$var is set even though it is empty';
}
?>
  •  Tags:  
  • php
  • Related