Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP implode not working for big array?

I have an array with 30k items, and implode returns nothing. No error message, no memory problems, just nothing.

If I use array_slice and slice the array to 100 items, it works fine. It also works for 7k array, but not for this one.

However, in another topic I found this code, which works just fine:

$arr = array();
for ($i = 0; $i < 50000; $i++) {
$arr[] = str_shuffle('This sentance is of average length, which The Internet says is  aboout 14.2 words.'); 
}
echo implode(PHP_EOL, $arr);

But with PHP_EOL I can't use that in my select, the string needs to be seperated by ','.

So I have two questions: is there any way to make this work and how can I catch this error? Because testing the implode output does not work, is_null, strlen, is_string, empty, isset, all these tests fail.

like image 830
Honza Avatar asked Feb 25 '14 13:02

Honza


1 Answers

EDIT: Facepalm moment after writing this answer that adding a for loop to make ? marks doesn't seem any better than just using it to output the data. Anyway I suppose you could try

<?
 $questionMarks =implode(',',array_fill(0,sizeof($myarray),'?'));
?>

and see if that has more luck for you.

You can use parametrized queries to circumvent your issue.

<?php

$db = new PDO(...);

//$myarray is some random sized php array of potential myid values
$questionMarks='';

//check to see if runtime is acceptible for your applicaition
for ($i = 0; sizeof($myarray); $i++)
    $questionMarks=",?";
$questionMarks=substr($questionMarks,1,strlen($questionMarks)-1);

/* you could try implode(',',array_fill(0,sizeof($myarray),'?')) but as you said implode might not work */

$sql = 'select myfield from mytable where myid in ('.$questionMarks.')';
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($myarray);
if (!$sth) {
    echo "\nPDO::errorInfo():\n";
    print_r($db->errorInfo());

}  


while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
   echo $row['myfield']  . "<br />";
}
?>
like image 116
ladieu Avatar answered Oct 21 '22 02:10

ladieu