explode not working for sure?

0

I have a variable that will fetch a string from the database.

I use explode to split the string and make it into a array , so that it can be displayed later.

However, when I use a for , it becomes infinite.

Here's my code.

String example: $string="array.jpg,teste.pdf,word.docx"

$count=explode(",", $string);
for($i=0; $i<=$count; $i++){ 
   echo $count[$i];
}
    
asked by anonymous 11.12.2017 / 20:00

1 answer

2

Within your for , you are comparing an integer value, $i , to an array , $count , and PHP thinks doing this comparison is quite normal and does not complains about this, but if you do well, it does not make sense. You need to compare two integer values and, as the second one should seem to be the size of the array , get that second value with count($count) :

<?php

$string="array.jpg,teste.pdf,word.docx";
$count=explode(",", $string);

for($i = 0; $i < count($count); $i++){ 
   echo $count[$i];
}

See working at Ideone | Repl.it

  

Notice that I also changed the operator from <= to < , since the indexing of array starts at zero and goes to n-1 , with no value in n . / p>

But the same result can be obtained with foreach :

<?php

$string="array.jpg,teste.pdf,word.docx";
$count=explode(",", $string);

foreach($count as $arquivo){ 
   echo $arquivo;
}

See working at Ideone | Repl.it

    
11.12.2017 / 20:13