简体   繁体   中英

Splitting Phone numbers

Got code below:

// $partInfo has data filled in
// $partinfo['BusinessPhone'] = '-567-5675678-'
// $billdata *should* have data filled in
// $billdata['BillingInfo']['telephone'] = ''
$telephone = explode('-', $billdata['BillingInfo']['telephone']);
echo "<!-- Telephone: ". print_r($telephone, true)." -->";

produces:

<!-- Telephone: Array
(
    [0] => 
)
-->    

// if billdata billinginfo telephone is blank
if(count($telephone)==0) {
  $telephone = explode('-', $partinfo['BusinessPhone']);
}
echo "<!-- Telephone2: ". print_r($partinfo['BusinessPhone'], true)." -->";

produces:

<!-- Telephone2: -567-5675678- -->

But...

echo "<!-- Telephone3: ". print_r($telephone, true)." -->";

produces:

<!-- Telephone3: Array
(
    [0] => 
)
-->

I suppose that since count($telephone) returns 1 instead of an empty array, that that's where I'm going wrong. What would be the best way to do this?

From the Return Values section of the PHP documentation for explode :

If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned .

So what's happening is that since $billdata['BillingInfo']['telephone'] = '' contains an empty string, which does not contain the given delimiter, it is returning an array containing the given string.

What you can do instead is:

$telephone = false;
if ($billdata['BillingInfo']['telephone']) {
    $telephone = explode('-', $billdata['BillingInfo']['telephone']);
}

if (!$telephone) {
    $telephone = explode('-', $partinfo['BusinessPhone']);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM