Search code examples
phpsortingexplode

PHP explode and sort


I need to sort an exploded string to write into database.

With the code down below it works, but I was not able to detect the summary of arrays outside the foreach loop.

So $terms[0].$terms[1].$terms[2] was not correct.

Cause as example $terms[0].$terms[1].$terms[2].$terms[3] was required for 4 terms in string.

How could that be solved?

$terms = explode(";", "banana;apple;lemon");

sort($terms);

$length = count($terms);

for($x = 0; $x < $length; $x++) {

$terms[$x] = $terms[$x].'; ';
}

$sorted_terms = $terms[0].$terms[1].$terms[2]; // <<< should changed dynamically

$sql = mysqli_query($dbcon,"INSERT INTO mydatabase (terms) VALUES ('$sorted_terms')");

Solution

  • Simply use string concatenation. Use $terms1 as string in for loop.

    $terms1 = "";
    $terms = explode(";", "banana;apple;lemon");
    sort($terms);
    $length = count($terms);
    for($x = 0; $x < $length; $x++) {
    $terms1 .= $terms[$x].'; ';
    }
    
    //$sorted_terms = $terms[0].$terms[1].$terms[2];
    //$sql = mysqli_query($dbcon,"INSERT INTO mydatabase (terms) VALUES ('$sorted_terms')");
    $sql = mysqli_query($dbcon,"INSERT INTO mydatabase (terms) VALUES ('$terms1')");