1

I need to break an if statement somehow. Here is the code

public function userData($data) {
    //checks if user is in the database
    if (self::checkUserExist($data)==false) { 
        $userInfo = array();
        $userInfo['id'] = (isset($data->id)) ? $data->id : break;
        $userInfo['email'] = (isset($data->email)) ? $data->email : break;
        $this->conn->insert($userInfo, $Table); // inserts data!
    }
}

The break doesn't work here. I need to return some kind of error. I could say that the input data is invalid or something, the main point for this is to avoid data insertion in database if the data is invalid.

tomsv
  • 7,207
  • 6
  • 55
  • 88
Cardiner
  • 89
  • 1
  • 14
  • 2
    What you need to do is to [`return`](http://php.net/manual/en/function.return.php) from the function – pNre Sep 27 '13 at 08:40
  • I wouldn't recomment to `break` or `return` in this case anyway ... the `if()` statement is the right place to insert dependencies (that's what it's there for). – Christoph Diegelmann Sep 27 '13 at 08:48

4 Answers4

1

break breaks while/for loops. use return false

Juris Malinens
  • 1,251
  • 1
  • 9
  • 13
0

You cannot break the if; If that is your whole code, you may use the return statement; Also, you should not combine it with a ternary operator (? :') as that will cause a parse error:

PHP Parse error: syntax error, unexpected 'break' (T_BREAK) PHP Parse error: syntax error, unexpected return (T_RETURN)

Another approach, would be to use goto (I can hear the bashing coming, but take a look at this question: Examples of good gotos in c or c++)

Also there are obscure hacks like do { ... } while(0);

that allows you to use break, but don't use that - this is stupid :)

Community
  • 1
  • 1
Adam Zielinski
  • 2,774
  • 1
  • 25
  • 36
0

Use:

public function userData($data) {
     if (self::checkUserExist($data)==false && isset($data->id) && isset($data->email)) { //checks if user is in the database
            $userInfo = array('id' => $data->id,'email' => $data->email);
            $this->conn->insert($userInfo, $Table); // inserts data!
     }
}

Or return or to make it even worse: goto.

Christoph Diegelmann
  • 2,004
  • 15
  • 26
-1

Try below code:

public function userData($data) {
     if (self::checkUserExist($data)==false) { //checks if user is in the database
            $userInfo = array();
        $userInfo['id'] = (isset($data->id)) ? $data->id : break;
            $userInfo['email'] = (isset($data->email)) ? $data->email : break;
            if(!$this->conn->insert($userInfo, $Table)){
              $message = 'Error';
            }else{
                $message = 'Success';
            }
     }
   }
Chandresh M
  • 3,808
  • 1
  • 24
  • 48