3

I want to know what if a customer ID I was trying to load was invalid. When I do this:

$customer = Mage::getModel('customer/customer')->load(12345);

If this customer exists, I get the data.

The problem is, if the customer ID doesn't exist, I still get something:

array (size=2)
  'created_at' => string '2016-05-24T15:59:18+00:00' (length=25)
  'group_id' => string '1' (length=1)

I needed a way where I can sort of say,

if(!$customer) {....

or

if(count($customer) < 1) { ....

But since there is always something in the returned array, how can I really know if a customer exists in the database?

1 Answer 1

5

Most of the time, the right test is to check whether the loaded object has an ID.

if ($customer->getId()) {
    // This is an existing customer
} else {
    // This is not an existing customer
}
2
  • depends on the case, it's sometimes better to check if $customer is set at all. if ($customer && $customer->getId()) If $customer is null you get an error, because getId() doesn't exists. To be 100% sure, use try / catch
    – Pawel
    Oct 7, 2016 at 11:14
  • 1
    @Pawel well in the case of the OP, he's using load() on Mage::getModel('customer/customer'). So he will always get a Mage_Customer_Model_Customer object even if there's no customer with that id. That's how the load method works. Adding if ($customer) is useless as it'll always be true Oct 7, 2016 at 11:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.