If isset error

Hi folks , i wanted to know if this condition is right


if (isset($row = $this->rows[0])){
$row = $this->rows[0];
}

coz it gives me error. if i m doing it right, what is the right way?

The isset function returns true if a variable is set. What you’ve got there is you’re setting a variable inside of the function parentheses, which makes no sense.

What Im thinking you want to do is:

  • Check if $this->rows[0] exists
  • If so, set $row to it.

In which case:

if(array_key_exists(0, $this->rows)){
    $row = $this->rows[0];
}

or, less preferable,

if(isset($this->rows[0])){
    $row = $this->rows[0];
}

Or, the best approach IMO:

$row = reset($this->rows);

This makes sure the “array pointer” to the first element and returns it - i.e. sets $row to $this->rows[0] if that exists, otherwise sets it to false.

If you wanted to run further code if it exists you could use:

$row = reset($this->rows);
if(false !== $row){
    //It exists
}

If you then wanted to iterate through the elements, you could use next() which returns the next item. Check out PHP: reset - Manual and the related functions listed.

Have you tried this?


if (isset($this->rows[0])){
$row = $this->rows[0];

// do something with $row
}

What i am trying to do is see if value exist, if it doesn’t than just skip and move on

There is no need for the $row = inside the isset. That’s pointless and bizarre because you’re setting $row then checking if it is set.

What are you actually trying to do and what’s the error?