The correct way to count an array in PHP

Asked

Viewed 71 times

-1

I would like to ask a question, I have a script where I count the total of files of a directory and compare with the files of the bank, everything is working.

My question is this:: When I put a code to be displayed the errors, displays an error, however it is working, I simply ignore and I shoot the error display? or I am using the count wrong?

Warning: Count(): Parameter must be an array or an Object that Implements Countable in /example.php on line 69

ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); // Esse é o código que força mostrar o erro


 foreach($files as $file){
    if(!in_array($file, $images)){

      echo "Cerca de <b>" .count($file). "</b> arquivo(s) que não estão no banco de dados <p>"; //Ele diz que tem erro nessa linha

      echo "Nomes dos arquivos: <b>" . $file . "</b><br>"; 
    }
  }
  • It gives a warning, not error, as you are passing a value that is not an array in any case. Try to put a is_array($file) before using the count().

  • is_array($file) did not return anything... then, as is a warning, "no problem"

  • The is_array is to check if it is an array only, then you print the count

  • Thanks @Rbz, you already answered my question.

2 answers

0

in case you’re doing the wrong Count, you’re counting the $file index and not the $files array

try:

count($files)
  • Hello, I’d say no, that’s correct... but still, thank you for trying to help.

  • even tested?

  • Yes, this post was more of a "doubt", the codes are correct.

  • ata, ok. I was just answering this question:" or am I using the wrong Count?" where you said yes, was pq counting index and not the array, but ok.

0

From what you can tell, the variable $file contains the file name. If so, it is a variable of the string type, so it is error. For Count() to work, the $file variable has to be an array or object of a class that implements the interface Countable, as the error message is stating.

If you use Count($files), will stop displaying the error, but the logic may not be quite correct.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.