0

My request PHP file elaborates some Ajax POST data:

POST data

data[0][id]:359
data[0][position]:1
data[1][id]:321
data[1][position]:2
data[2][id]:354
data[2][position]:3

Request.php

if(isset($_POST['data'])) {
    if(isset($_SESSION['username']) && isset($_SESSION['password'])) {

        $verify = $loggedIn->verify();

        if($verify['username']) {
            $Profile = new Profile();
            $Profile->db = $db;
            //Call my function
            $messages = $Profile->setOrder($_POST['data']);     

        }
    }
}

Profile.php

function setOrder($post) {
    var_dump($post);

    foreach($post as $item)
    {
        return "Area ID ".$item["id"]." and person located ".$item["position"]."<br />";
    }
}

My function returns nothing and the dump of $post is as below

array(3) {
  [0]=>
  array(2) {
    ["id"]=>
    string(3) "359"
    ["position"]=>
    string(1) "1"
  }
  [1]=>
  array(2) {
    ["id"]=>
    string(3) "321"
    ["position"]=>
    string(1) "2"
  }
  [2]=>
  array(2) {
    ["id"]=>
    string(3) "354"
    ["position"]=>
    string(1) "3"
  }
}

Inside my function I can dump correctly something like var_dump($post[0]["id"]); so why my foreach loop is empty?

4
  • Try to var_dump($item); inside the loop. Maybe it will reveal something. Commented Oct 18, 2017 at 14:27
  • 2
    You're not actually telling your foreach() to output anything, merely return - which will assign that string to $messages = $Profile->setOrder($_POST['data']); and terminate the loop. Commented Oct 18, 2017 at 14:28
  • 2
    you don't loop because return breaks the loop Commented Oct 18, 2017 at 14:28
  • I missed the return. Do you want to echo? Commented Oct 18, 2017 at 14:29

1 Answer 1

2

It is because you are using return inside loop. It will terminate the loop after first iteration. You need to do something like this.

$return = null;
foreach($data as $item)
{
    $return .= "Area ID ".$item["id"]." and person located ".$item["position"]."<br />";
}
return $return;
Sign up to request clarification or add additional context in comments.

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.