简体   繁体   中英

PHP: foreach loop assign the values of an array to a concatenated string and variable

I want to assign the values of an array to a string with a variable:

    $my_array_values = array("apple", "orange", "cellular", "box");

//my function
function my_function ($my_array_values, $string) {
foreach ($my_array_values as $my_array_value) {
$string_query = $string;
 echo $string_query . "<br>";
}
}

//string to loop the variable inside the foreach
$string_variable = "SELECT login FROM table WHERE login = '" . $my_array_value . "'";
my_function ($my_array_values, $string_variable);

If I echo it, the result is this (not taking the array values of the variable):

    SELECT login FROM table WHERE login = ''
SELECT login FROM table WHERE login = ''
SELECT login FROM table WHERE login = ''
SELECT login FROM table WHERE login = ''

The result should be like this:

    SELECT login FROM table WHERE login = 'apple'
SELECT login FROM table WHERE login = 'orange'
SELECT login FROM table WHERE login = 'cellular'
SELECT login FROM table WHERE login = 'box'

How I can do that? Kind regards

What is it you are trying to achieve? The MySQL IN function looks for values "IN" a subset or other pool of info.

$query= "SELECT login FROM table WHERE login IN ({implode(',', $my_array_values)})";

Would this be easier than looping over and over?

The correct way is like this:

$my_array_values = array("apple", "orange", "cellular", "box");

//my function
function my_function ($my_array_values, $string) {
  foreach ($my_array_values as $my_array_value) {
    $string_query = $string . $my_array_value . "'";
     echo $string_query . "<br>";
  }
}

//string to loop the variable inside the foreach
$string_variable = "SELECT login FROM table WHERE login = '" ;
my_function ($my_array_values, $string_variable);

No need to create extra variables in your function. Simply echo what was passed along with the value extracted from the array that was passed.

$my_array_values = array("apple", "orange", "cellular", "box");

//my function
function my_function ($my_array_values, $string) {

    foreach ($my_array_values as $my_array_value) {
        echo $string . $my_array_value . "'<br>";
    }

}  // end of my_function

//string to loop the variable inside the foreach
$string_variable = "SELECT login FROM table WHERE login = '";
my_function ($my_array_values, $string_variable);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM