Explode not working for sure?

Asked

Viewed 56 times

0

I have a variable that picks up a string to the database.

I use explode to split the string and turn into a array, to be presented later.

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

Here is my code.

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

$count=explode(",", $string);
for($i=0; $i<=$count; $i++){ 
   echo $count[$i];
}
  • 3

    $i<=$count, you are comparing an integer number with a array. Didn’t miss the function count() there, no? Consider using the structure foreach, also; should simplify the code.

  • @Andersoncarloswoss I had this function but I couldn’t implement it either. It could help me to implement?

  • your variable Count is getting the result of the string explode, not the size of the explode, so the for won’t work properly. from a look at this url, it explains the logic of a for in a variable that receives an https://stackoverflow.com/questions/16502748/php-count-the-number-of-strings-after-explodedarray

  • 1

    Uses a foreach same. So you don’t need to count or calculate the number of rudders in the array.

1 answer

2


Within your for, you are comparing an entire value, $i, with a array, $count, and PHP thinks that making this comparison is something quite normal and does not complain about it, but if you choose well, it does not make sense. You need to compare two integer values and, as the second apparently should be the size of the array, obtain 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 on Ideone | Repl.it

Note that I also changed the operator of <= for <, because the indexation of array starts at zero and goes up to n-1, there is no value in n.

But the same result can be obtained with the foreach:

<?php

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

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

See working on Ideone | Repl.it

  • <= was a mistake I often get by distraction, because I have the addiction to always getting values in 0. Thank you so much for your help, I will give your reply as accepted soon! Besides, I never thought that the foreach was so easy to use!

Browser other questions tagged

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