2

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.

3 Answers 3

2

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

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

3 Comments

Jup, I used the following which worked, if(!is_null($id)). Thanks!
@Chris yes if(!is_null($id)) will evaluate to true when $id == '0' is that what you want? I thought you didn't want to go into the first block when the value of $id` is anything except null?
I moved the else to be the first if. So now it will first check if $id is not null
1

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)) {

4 Comments

Still runs the first if.
I updated my answer with what you might be looking for.
I've tried if(!empty($id)) but it still doesn't run the else
Whoops, that should be if(empty($id)). I'll fix that.
0

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).

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.