0

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?

6
  • 1
    You are trying to loop over a string not an array. Commented Sep 10, 2018 at 9:29
  • Are you getting (45,42,12,) or 45,42,12, in post data? Commented Sep 10, 2018 at 9:29
  • you should foreach the original array Commented Sep 10, 2018 at 9:30
  • You have to explode string Commented Sep 10, 2018 at 9:34
  • 1
    if you get "45,42,12," in your POST (with the trailing ",") you should also fix what you are sending. Commented Sep 10, 2018 at 9:38

4 Answers 4

6

If your final string is 45,42,12 then you can use explode function of PHP

$finalArray = explode(",",$str);

foreach ($finalArray as $value) {

}
Sign up to request clarification or add additional context in comments.

2 Comments

This is the correct solution, instead of using string to foreach you should use an Array.
@mvasco Please accepts the correct answer because it's useful for other users in future.
1

Before looping, you need to have an array. You probably want to explode the string:

$array = explode(',', $str);
foreach ($array as $value) {
 // code here...
}

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.