arrays - PHP - Skip object of class null

620

I am pulling data from my database on specific entity and form other tables related to them.

How can I skip an error when some object is null in db?

Error is:

Call to a member function getName() on null

Code:

$results = $this->getMyRepository()->findAll();

    $rows = [];

    $rows[] = array(
        "id",
        "user",
        "category"
    );

    foreach ($results as $row) {
        $rows[] = [
            $row->getId(),
            $row->getUser()->getFullName(),
            $row->getCategory()->getName(),
        ];
    }
    return $rows;
}
150

Answer

Solution:

This is not an error, but exception. Errors might be suppressed by "@" operator.

You can't just skip exception. To handle them you need to use try-catch block.

Perhaps you want to check if user and category exists. Your code might look like this below (using ternary operator).

foreach ($results as $row) {
    $rows[] = [
        $row->getId(),
        ($user = $row->getUser()) ? $user->getFullName() : null,
        ($category = $row->getCategory()) ? $category->getName() : null,
    ];
}
792

Answer

Solution:

You can simply check if the variable is null before working with it

 foreach ($results as $row) {
      $rows[] = [
        $row->getId(),
        $row->getUser()->getFullName(),
        !is_null($row->getCategory()->getName()) ? $row->getCategory()->getName() : '',
      ];
   }

Documentation: is_null

People are also looking for solutions to the problem: php - zend update is deleting old values

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.