Reputation: 5107
I am working on a PHP file.
There is a string array that I receive via POST:
$str = (45,42,12,);
First I remove the last comma:
$str = substr($string_temas,0,-1);
I get then
$str = (45,42,12);
To check it, I echoed it:
echo "str value=".$str;
And I get as echo result:
str value=45,42,12
Then I try to loop for each item, like this:
foreach ($str as $value) {
}
but I am getting an error:
Invalid argument supplied for foreach() in .....line (foreach ($str as $value) {
What am I doing wrong?
Upvotes: 0
Views: 125
Reputation: 1364
If your final string is 45,42,12 then you can use explode function of PHP
$finalArray = explode(",",$str);
foreach ($finalArray as $value) {
}
Upvotes: 6
Reputation: 340
You'll only receive a string from request data, not an array. Use explode to split comma separated data into an array
$arr=explode(',',$str);
Then you can loop through this.
Upvotes: 1
Reputation: 194
because you loop string variable. To convert string to array, you can use explode function.
foreach (explode(",", $str) as $value) {
...
}
http://php.net/manual/en/function.explode.php https://www.w3schools.com/php/func_string_explode.asp
Upvotes: 1
Reputation: 8249
Before looping, you need to have an array. You probably want to explode the string:
$array = explode(',', $str);
foreach ($array as $value) {
// code here...
}
Upvotes: 1