/    Sign up×
Community /Pin to ProfileBookmark

concatenating phone numbers with commas and spaces

I have three phone number fields: $PhoneHome, $PhoneWork, and $Mobile. They all may or may not contain data.

I want to concatenate them, and have “(h)”, “(w)”, and “(m)” at the end of each. I also want commas between them.

I have some code which works, but it’s quite long-winded. Is there an easier way of doing it?

[code=php]$NumPhones=0;
if ($PhoneHome!=”) {$NumPhones++;}
if ($PhoneWork!=”) {$NumPhones++;}
if ($Mobile!=”) {$NumPhones++;}

if ($NumPhones==3)
{
$Phone = ($PhoneHome . ‘ (h), ‘ . $PhoneWork . ‘ (w), ‘ . $Mobile . ‘ (m)’);
}

if ($NumPhones==2)
{
if ($PhoneHome!=” && $PhoneWork!=”)
{
$Phone=($PhoneHome . ‘ (h), ‘ . $PhoneWork . ‘ (w)’);
}
if ($PhoneHome!=” && $Mobile!=”)
{
$Phone=($PhoneHome . ‘ (h), ‘ . $Mobile . ‘ (m)’);
}
if ($PhoneWork!=” && $Mobile!=”)
{
$Phone=($PhoneWork . ‘ (h), ‘ . $Mobile . ‘ (m)’);
}
}
if ($NumPhones==1)
{
if ($PhoneHome!=”)
{
$Phone=($PhoneHome . ‘ (h)’);
}
if ($PhoneWork!=”)
{
$Phone=($PhoneWork . ‘ (w)’);
}
if ($Mobile!=”)
{
$Phone=($Mobile . ‘ (w)’);
}
}
[/code]

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@GarySJun 02.2006 — No replies yet?

Here's one way to do it... using an array:

[code=php]
//Three numbers
$phone=array('h'=>'home_number',
'w'=>'work_number',
'm'=>'mobile_number');

//Two numbers
//$phone=array('h'=>'home_number',

// 'm'=>'mobile_number');

//One number
//$phone=array('m'=>'mobile_number');


//print_r($phone);

$counter=0;
foreach($phone as $name=>$value){

if($counter!=0){
echo ', ';
}

echo $value . ' ('. $name . ')';
$counter++ ;
}
[/code]
Copy linkTweet thisAlerts:
@NogDogJun 02.2006 — [code=php]
foreach(array('h' => $PhoneHome,
'w' => $PhoneWork,
'm' => $Mobile) as $key => $val)
{
$Phone .= (!empty($val)) ? " $val ($key)," : "" ;
}
$Phone = trim($Phone, ", ");
[/code]
Copy linkTweet thisAlerts:
@GarySJun 02.2006 — Nice ?
Copy linkTweet thisAlerts:
@Colm_OsirisauthorJun 02.2006 — Thanks to Gary and NogDog. I've not used arrays yet, so will experiment with this.
×

Success!

Help @Colm_Osiris spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...