I am trying to see if an array contains a specific set of strings. In my specific situation, I have an array that contains customer addresses. I am trying to see if every address is a PO Box or not. I want to print an error message if all of their addresses are PO Boxes.
This is what I currently have.
public function checkPhysicalAddressOnFile(){
$customer = Mage::getSingleton('customer/session')->getCustomer();
foreach ($customer->getAddress() as $address) {
if stripos($address, '[p.o. box|p.o box|po box|po. box|pobox|post office box]') == false {
return false
Here is how I would approach it:
public function checkPhysicalAddressOnFile(){
$addresses = Mage::getSingleton('customer/session')->getCustomer()->getAddresses();
foreach($addresses AS $address) {
if(!preg_match("/p\.o\. box|p\.o box|po box|po\. box|pobox|post office box/i", $address)) {
// We found an address that is NOT a PO Box!
return true;
}
}
// Apparently all addresses were PO Box addresses, or else we wouldn't be here.
return false;
}
Your code was pretty close to working already, you mainly just needed the preg_match
function to check against a regex pattern.
Here's a more terse option:
public function checkPhysicalAddressOnFile() {
return (bool) count(array_filter(Mage::getSingleton('customer/session')->getCustomer()->getAddresses(), function($address) {
return !preg_match("/p\.o\. box|p\.o box|po box|po\. box|pobox|post office box/i", $address);
}));
}
See here for an example: https://3v4l.org/JQQpA