Reputation: 43
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
Upvotes: 0
Views: 497
Reputation: 390
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?
Upvotes: 1
Reputation: 5191
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);
Upvotes: 0
Reputation: 663
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);
Upvotes: 0