Magento – Check if customer has address

customer-addressmagento-1.9

I am programmatically creating customers and adding billing and shipping addresses to their accounts.

I have put in $customer->loadByEmail($email) so when this script runs a second time it updates a customer instead of saving them again.

At the moment I can not work out how to check if a customer has a specific billing or shipping address (or other additional address) when I want to add an address, so I am re-adding the same addresses when the script runs again.

How do I check if a customer has a specific address?

e.g.

$address_details = array(
    'firstname'  => $firstname,
    'lastname'   => $lastname,
    'street'     => array(
        '0'      => $line1,
        '1'      => $line2,
    )
    'city'       => $city,
    'postcode'   => $postcode,
    'country_id' => 'GB',
    'telephone'  => $tel,
    'parent_id'  => $customer->getId(),
);

if(!$customer->hasAddress($address_details)) {
    //add address
}

I would prefer to steer away from a massive foreach such as:

$customer = Mage::getSingleton('customer/session')->getCustomer();
$hasAddress=false;
foreach ($customer->getAddresses() as $address) {
    if($address->getCity() !== $city) {
        $hasAddress = true;
    }
    //...
}

Best Answer

$customer->getAddresses() should return all customer addresses so count($customer->getAddresses()) should return quantity of addresses of customer.

you can check like

if(count($customer->getAddresses()) >= 0)
{
    //Customer has one or more addresses. Your code here
}
Related Topic