How to know if I am in the last iteration of a foreach

4

I have a function that concatenates a query from POST variables, this I do with a foreach:

$id = $_POST['empId'];
$query = "UPDATE userInfo SET ";
foreach ($_POST as $key => $value) {
    $query .= "$key = '$value', ";
}
$query .= " WHERE id = '$id'";

How can I know when is the last iteration to be able to remove the final comma in the last iteration and thus be able to construct the query correctly?

    
asked by Fernando Garcia 15.05.2018 в 21:30
source

3 answers

0

You can use the php array function end () . The function, as you can read in the link, establishes the pointer in the last element of the array. If you evaluate it with a conditional, you can achieve what you propose in a fairly clean and efficient way;

$id = $_POST['empId'];
$query = "UPDATE userInfo SET ";
$keys = array_keys($_POST);
foreach ($_POST as $key => $value) {
    if ($key === end($keys)) {
        $query .= "$key = '$value'";
    } else {
        $query .= "$key = '$value', ";
    }
}
$query .= " WHERE id = '$id'";
    
answered by 15.05.2018 / 22:36
source
6

You can achieve what you want with the implode function, instead of concatenating to the string adds elements to an array and finally you do implode

$id = $_POST['empId'];
$query = "UPDATE userInfo SET ";
$queryParams = array();
foreach ($array as $key => $value) {
    $queryParams[] = "$key = '$value'";
}
$params = implode(', ', $queryParams);
$query = $query . $params . " WHERE id = '$id'";

As a side note, it seems that you are exposed to an attack by SQL Injection , in this post you speak in an extended manner on how to avoid it: How to avoid SQL injection in PHP?

    
answered by 15.05.2018 в 21:46
1

It's simple, you should only check the keys of the arrangement and then check if you are actually in the last

<?php

//Leo cuantos elementos hay en el array
$cont = count($_POST);
//Consulto las keys del array
$keys = array_keys($_POST);
//Busco la ultima
$ultima_key = $keys[$cont-1];

foreach ($_POST as $key => $value) {
    if($key == $ultima_key){
        echo "Esta es la ultima iteracion\n";
    }else{
        echo "Esta no es la ultima iteracion\n";
    }    
}

?>
    
answered by 15.05.2018 в 22:03