-5

I got this code from google and it fulfills my requirement, but I don't understand the meaning of this line:

substr($query,0,strlen($query)-2)

Could somebody explain it to me?

<?php
function insert($tablename, $parameter_order, $values)
{
    $query = "insert into $tablename (";
    foreach($parameter_order as $po)
    {
        $query .= $po.', ';
    }
    $query = substr($query,0,strlen($query)-2).') values (';
foreach($values as $v)
{
$query .= "'$v', ";
}
$query = substr($query,0,strlen($query)-2).');';
    return $this->makeQuery($query);
}
?>
TZHX
  • 5,291
  • 15
  • 47
  • 56
Mani Kandan
  • 699
  • 1
  • 10
  • 30

2 Answers2

1

The line removes the last comma and space from $query. These characters have been added in the foreach loop to glue together the elements of $parameter_order.

Note that this standard task is usually done better with the implode() function:

$query = "insert into $tablename (" . implode (', ', $parameter_order) . ' ) values (';
Michael Jaros
  • 4,586
  • 1
  • 22
  • 39
  • Your confusing me.. Where will this line fit exactly in my code – Mani Kandan Apr 25 '15 at 07:50
  • 1
    @ManiKandan: I wrote this line for you to learn, not to put it in your code. You usually use a statement like that instead of a `foreach` loop if you want to concatenate elements of an array. If you have no idea what I'm talking about, maybe you should start with some basic PHP tutorials. – Michael Jaros Apr 25 '15 at 07:55
1

This is what those functions do exactly:

substr() is used to generate a sub-string of specified length from another string.

strlen() will return the length of the provided string.

Code substr($query,0,strlen($query)-2) removes comma and space from foreach Loop.

Community
  • 1
  • 1
Hardik Bharadava
  • 472
  • 1
  • 9
  • 22