Hardist
Hardist

Reputation: 1993

Remove last comma from foreach array result

I have this small function that let's me update any table and any values that I submit via a form. This is for personal use and no security is needed. But I need to remove the last comma from the script. First, here is the code:

public function updateForm($table, $formValues, $formID)
{
    foreach ($formValues as $key => $val)
    {
        $form = "$key = '$val', ";
        $this->mysqli->query("UPDATE `$table` SET $form WHERE id = '$formID'");
    }
}

If I submit 3 fields called field1, field2, and field3 which contain the values test1, test2 and test3, the $form will look like this:

field1 = 'test1', field2 = 'test2', field3 = 'test3',

But that last comma needs to be gone. How would I accomplish this? I have tried everything I can think of, including rtrim($form,','); - But this also does not remove the last comma from the populated values.

Any shove into the right direction would be greatly appreciated :)

Upvotes: 1

Views: 585

Answers (2)

Fleshgrinder
Fleshgrinder

Reputation: 16273

Another approach that doesn't require any kind of counting.

<?php

$string = null;
foreach ($array as $key => $value) {
  $string && ($string .= ", ");
  $string .= "{$key} = '{$value}'";
}

This always works and is ultra fast.

Upvotes: 2

Abhineet Verma
Abhineet Verma

Reputation: 1028

First bring $this->mysqli->query("UPDATE$tableSET $form WHERE id = '$formID'"); outside of foreach loop.

Now, you can check last index if array while traversing it in a foreach loop.

public function updateForm($table, $formValues, $formID)
{
    foreach ($formValues as $key => $val)
    {
        $last_key = key( array_slice( $array, -1, 1, TRUE ) ); // Checks for array last index
        if ('key' == $last_key) {
            $form = "$key = '$val', ";      
        }
        else
            $form = "$key = '$val' ";
    }

    $this->mysqli->query("UPDATE `$table` SET $form WHERE id = '$formID'");
}

This will provide you output like this

field1 = 'test1', field2 = 'test2', field3 = 'test3'

You can also use end() to get last index but, array_slice() is quiet faster that end()

To check last index using end()

end(array_keys($myarr))

Upvotes: 2

Related Questions