elad.chen elad.chen - 1 year ago 66
PHP Question

rtrim fails with very long strings

I'm building a very large query string, (8000 raws, using it only once in a million years.) I need to get rid of the final comma, which is added while the string is being built.

Take a look at my code, for some reason it as if

does nothing to it; the
string passed into
returns completely intact.

(If you need a copy of the value of query_string value, let me know and I'll upload it too.)

public function sync_sites_table()

# $query_string = "TRUNCATE TABLE " . self::$table_name;
# $db->query($query_string);


$query_string = "INSERT INTO `".self::$table_name . "` (`site_id`, `site_name`) VALUES \n";

foreach($this->sites_array as $key => $value)
$query_string .= "('".$key."','".$value."'), \n";

rtrim($query_string, ",");

global $db;


Answer Source

rtrim() isn't pass by reference; it returns the trimmed value which you need to assign to a variable:

$query_string = rtrim($query_string, ",");

But a cleaner answer might be:

$first = true;
foreach($this->sites_array as $key => $value)
    if (!$first) { $query_string .= ', '; } else { $first = false; }
    $query_string .= "('".$key."','".$value."') \n";

so you wouldn't need to trim any trailing ,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download