Chris
Chris

Reputation: 1654

PHP function not seeing value of second parameter

For some odd reason my PHP is not seeing the value of the second parameter.

My code:

PHP function:

public function getVacs($key, $id = null, $deleted = null, $deleted_key = null) {

        if(!$id) {
            $data = $this->_db->getAll('vacatures', $key);
        } elseif(!empty($deleted)) {
            $data = $this->_db->getAll('vacatures', $key, $id, $deleted, $deleted_key);
        } else {
            $data = $this->_db->getAll('vacatures', $key, $id);
        }

        if($data->count()) {
            $this->_data = $data->results();
            $this->_count = $data->count();
            return true;
        }
    }

Calling the function:

} elseif(isset($_POST['all'])) {

        $vacs = $v->getVacs('delete', '0');

        echo json_encode($v->data());
        exit();
    }

The problem is, the function does not see the value of $id.

It's running the first if while it should be running the else.

Upvotes: 2

Views: 115

Answers (3)

RockTheShow
RockTheShow

Reputation: 328

Using the strict comparison operator might be a good idea in these cases (and I would say in most cases):

0 == null; // evaluates to true
0 === null; // evaluates to false

Useful with strpos also (returns 0 means searched term at position 0 of haystack string, returns false means searched term not found).

Upvotes: 0

Ray
Ray

Reputation: 41428

In php the string "0" evaluates to false.

This means your check if(!$id) will evaluate to true and by your logic id won't be set in $data.

If the string "0" is legitimate option, then check for null explicitly instead:

if(is_null($id)){ 

This will

Upvotes: 2

aynber
aynber

Reputation: 23011

It is seeing the value of $id, but your if statement is set up wrong. 0 will evaluate to false on a check like that. So you really need to make sure that it's not null:

 if($id != null) {

If you want the first if to run only if there is NOT a valid id, then you need to check if it's empty (i.e. not null, 0, false, or an empty string)

if(empty($id)) {

Upvotes: 1

Related Questions