Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

String together multiple variables and seperate with commas

Posted on 2011-10-04
10
Medium Priority
?
217 Views
Last Modified: 2013-11-05
I have 6 variables:

$faxnumber
$faxnumber2
$faxnumber3
$faxnumber4
$faxnumber5
$faxnumber6

Each of these variables can be equal to a fax number (5555551212) OR can be null (0000000000).  The numbers need to be passed to a new variables called $faxnumbers.  $faxnumbers is equal to all of the numbers seperated by commas -

$faxnumbers = "$faxnumber,$faxnumber2,$faxnumber3,$faxnumber4,$faxnumber5,$faxnumber6";

I no longer want to include the variable if it is equal to 0000000000.  So... I need to remove the variable from the above string if equal to 0000000000, BUT I also need to remove the , that seperates it.

Any suggestions?
0
Comment
Question by:hypervisor
  • 3
  • 2
  • 2
  • +2
10 Comments
 
LVL 5

Accepted Solution

by:
PragmatiCoder earned 2000 total points
ID: 36914361
First i have to say that it would be much easier and dynamic if you store the fax numbers in an array as $faxnumber[1], $faxnumber[2], ... , $faxnumber[n] so it is not limited to only 6 fax numbers...

But with the description given:

<?php
    $faxnumber = "0000000000";
    $faxnumber2 = "0000000002";
    $faxnumber3 = "0000000003";
    $faxnumber4 = "0000000004";
    $faxnumber5 = "0000000005";
    $faxnumber6 = "0000000006";

    $faxnumbers = '';

    for($i = 0; $i < 7; $i++){
        $i = $i == 0 ? '' : $i;//Avoid printing a 0 in the variable name
        if($faxnumber.$i != '0000000000')//Concat only if fax number is different to 0000000000
            $faxnumbers .= $faxnumber.$i.', ';
    }
    $faxnumbers = substr($faxnumbers, 0, -2);//Remove the last ", "
    echo $faxnumbers.'<br />';
?>

Open in new window


Now in case you were using arrays...

<?php
    $faxnumber[0] = "0000000000";
    $faxnumber[1] = "0000000002";
    $faxnumber[2] = "0000000003";
    $faxnumber[3] = "0000000004";
    $faxnumber[4] = "0000000005";
    $faxnumber[5] = "0000000006";
    
    $faxnumbers = '';
    
    foreach($faxnumber as $f){
        if($f != '0000000000')
            $faxnumbers .= $f.', ';
    }
    
    echo $faxnumbers;
?>

Open in new window


Also if you use arrays and don't have to check for values you could just use implode(",",$faxnumber);
0
 

Author Comment

by:hypervisor
ID: 36914366
Hmm, with this code you get a trailing , on the last result:

0000000002, 0000000003, 0000000004, 0000000005, 0000000006,

That's part of the issue I was having.
0
 
LVL 10

Expert Comment

by:Derokorian
ID: 36914544
substr($faxnumbers,0,-1);
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 10

Expert Comment

by:Derokorian
ID: 36914561
Actually i didn't see that it also has a trailing space so it would be:

$faxnumbers = substr($faxnumbers,0,-2);
0
 
LVL 10

Expert Comment

by:Derokorian
ID: 36914579
Also arrays are definitely better, however I would do it differently:

<?php
   $faxnumber = array();
   $faxnumber[0] = "0000000000";
   $faxnumber[1] = "0000000002";
   $faxnumber[2] = "0000000003";
   $faxnumber[3] = "0000000004";
   $faxnumber[4] = "0000000000";
   $faxnumber[5] = "0000000005";
   $faxnumber[6] = "0000000006";
   $faxnumber[7] = "0000000000";

   $empty = '0000000000';
   
   $faxnumber = array_filter($faxnumber,function($element) use ($empty) { return ($element != $empty); } );
   $faxnumbers = implode(', ',$faxnumber);
   
   echo $faxnumbers;

?>

Open in new window

0
 

Author Comment

by:hypervisor
ID: 36914669
Any idea why won't work?

<?php

// only allow posting of the form from a defined URL
 
    $faxnumber[0] = "".$_POST['faxnumber']."";
    $faxnumber[1] = "".$_POST['faxnumber2']."";
    $faxnumber[2] = "".$_POST['faxnumber3']."";
    $faxnumber[3] = "".$_POST['faxnumber4']."";
    $faxnumber[4] = "".$_POST['faxnumber5']."";
    $faxnumber[5] = "".$_POST['faxnumber6']."";
    
    $faxnumbers = '';
    
    foreach($faxnumber as $f){
        if($f != '0000000000')
            $faxnumbers .= $f.';';
    }
    
    $fax_reform = substr($faxnumbers,0,-1);
   echo "hello";
   echo $faxnumbers;
    echo $fax_reform;
    
    ?>

Open in new window

0
 
LVL 1

Expert Comment

by:ob2s
ID: 36914727
Hi,

If you're sure there will only be digits, you could keep it simple and take advantage of automatic type conversion -- just have apply_filter() call intval().  The all-zeros case will convert to false and the others will convert to true.

<?php
   $faxnumber = array();
   $faxnumber[0] = "0000000000";
   $faxnumber[1] = "0000000002";
   $faxnumber[2] = "0000000003";
   $faxnumber[3] = "0000000004";
   $faxnumber[4] = "0000000000";
   $faxnumber[5] = "0000000005";
   $faxnumber[6] = "0000000006";
   $faxnumber[7] = "0000000000";

   $faxnumber = array_filter($faxnumber, 'intval');
   $faxnumbers = implode(', ',$faxnumber);

   echo $faxnumbers;
?>

Open in new window

0
 
LVL 5

Expert Comment

by:PragmatiCoder
ID: 36916964
The first code i posted didn't leave any trailing... anyway

Create a new php file and paste the code below:

<?php
if(isset($_POST['form_faxnumbers'])){ 
    $post_faxnumbers = $_POST['form_faxnumbers'];
    $faxnumbers = array_filter($post_faxnumbers,'intval');
    $faxnumbers = implode(';',$faxnumbers);

    echo($faxnumbers);
}
?>

<form method="POST">
    <input type="hidden" name="form_faxnumbers[]" value="0000000000" />
    <input type="hidden" name="form_faxnumbers[]" value="0000000001" />
    <input type="hidden" name="form_faxnumbers[]" value="0000000002" />
    <input type="hidden" name="form_faxnumbers[]" value="0000000003" />
    <input type="hidden" name="form_faxnumbers[]" value="0000000004" />
    <input type="hidden" name="form_faxnumbers[]" value="0000000005" />
    <input type="hidden" name="form_faxnumbers[]" value="0000000006" />
    <input type="hidden" name="form_faxnumbers[]" value="0000000000" />
    <input type="submit" />
</form>

Open in new window

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 36918260
Implode() is the right function to convert arrays into strings.
http://php.net/manual/en/function.implode.php

If you must process the elements of the array (such as sanitize inputs or make decisions about what to keep with if() statements) you can use the concatenation operator to add a comma to the end of each element as you build the string.  Then you use rtrim() to remove the extraneous comma.
http://php.net/manual/en/language.operators.string.php
http://php.net/manual/en/function.rtrim.php

If you want to be nice to your clients, you might consider that phone numbers are written, by people, in many different ways.  All of 703.346.0600 and (703) 346-0600 and 1-703-346-0600 are equally useful representations of my phone number.  However you need to normalize the numbers for use in programmatic representations.  This function will do that for you.
<?php // RAY_phone_numbers.php - USING USA PHONE NUMBERS
error_reporting(E_ALL);

// A FUNCTION TO VALIDATE A PHONE NUMBER AND RETURN A NORMALIZED STRING
// MAN PAGE: http://discuss.fogcreek.com/joelonsoftware3/default.asp?cmd=show&ixPost=102667&ixReplies=15
function strtophone($phone, $format=FALSE, $letters=FALSE, $dlm='-')
{
    if ($letters)
    {
        // TRANSLATE INPUT LIKE 1-800-BIG-DOGS
        $phone = strtoupper($phone);
        if (preg_match('/[A-Z]/', $phone))
        {
            $phone = str_replace('A', '2', $phone);
            $phone = str_replace('B', '2', $phone);
            $phone = str_replace('C', '2', $phone);

            $phone = str_replace('D', '3', $phone);
            $phone = str_replace('E', '3', $phone);
            $phone = str_replace('F', '3', $phone);

            $phone = str_replace('G', '4', $phone);
            $phone = str_replace('H', '4', $phone);
            $phone = str_replace('I', '4', $phone);

            $phone = str_replace('J', '5', $phone);
            $phone = str_replace('K', '5', $phone);
            $phone = str_replace('L', '5', $phone);

            $phone = str_replace('M', '6', $phone);
            $phone = str_replace('N', '6', $phone);
            $phone = str_replace('O', '6', $phone);

            $phone = str_replace('P', '7', $phone);
            $phone = str_replace('Q', '7', $phone);
            $phone = str_replace('R', '7', $phone);
            $phone = str_replace('S', '7', $phone);

            $phone = str_replace('T', '8', $phone);
            $phone = str_replace('U', '8', $phone);
            $phone = str_replace('V', '8', $phone);

            $phone = str_replace('W', '9', $phone);
            $phone = str_replace('X', '9', $phone);
            $phone = str_replace('Y', '9', $phone);
            $phone = str_replace('Z', '9', $phone);
        }
    }

    // DISCARD NON-NUMERIC CHARACTERS
    $phone = preg_replace('/[^0-9]/', NULL, $phone);

    // DISCARD A LEADING '1' FROM NUMBERS ENTERED LIKE 1-800-555-1212
    if (substr($phone,0,1) == '1') $phone = substr($phone,1);

    // IF LESS THAN TEN DIGITS, IT IS INVALID
    if (strlen($phone) < 10) return FALSE;

    // IF IT STARTS WITH '0' OR '1' IT IS INVALID, SECOND DIGIT CANNOT BE '9' (YET)
    if (substr($phone,0,1) == '0') return FALSE;
    if (substr($phone,0,1) == '1') return FALSE;
    if (substr($phone,1,1) == '9') return FALSE;

    // ISOLATE THE COMPONENTS OF THE PHONE NUMBER
    $ac = substr($phone,0,3); // AREA
    $ex = substr($phone,3,3); // EXCHANGE
    $nm = substr($phone,6,4); // NUMBER
    $xt = substr($phone,10);  // EXTENSION

    // ADD OTHER TESTS HERE AS MAY BE NEEDED - THESE ARE FOR LOCAL APPS
    if ($ac == '900') return FALSE;
    if ($ac == '976') return FALSE;
    if ($ex == '555') return FALSE;

    // IF NOT FORMATTED
    if (!$format) return $phone;

    // STANDARDIZE THE PRINTABLE FORMAT OF THE PHONE NUMBER LIKE 212-555-1212-1234
    $formatted_phone = $ac . $dlm . $ex . $dlm . $nm;
    if ($xt != '') $formatted_phone .= $dlm . $xt;
    return $formatted_phone;
}



// DEMONSTRATION OF THE FUNCTION IN ACTION.
if (!empty($_GET["phone"]))
{

    // VALIDATE PHONE USING FUNCTION ABOVE
    if (!$phone = strtophone($_GET["phone"], TRUE))
    {
        // FUNCTION RETURNS FALSE IF PHONE NUMBER IS UNUSABLE
        echo "BOGUS: {$_GET["phone"]} ";
    }
    else
    {
        // SHOW THE FORMATTED PHONE
        echo "VALID: {$_GET["phone"]} == $phone";
    }
}


// END PHP, PUT UP THE FORM TO TEST PHONE NUMBERS
?>
<form>
ENTER A PHONE NUMBER:
<input name="phone" /><br/>
<input type="submit" />
</form>
TRY SOME OF THESE (COPY AND PASTE):
<br/>1-800-5551212
<br/>202-537-7560
<br/>202 537 7560
<br/>1-202-537-7560
<br/>(202) 537-7560
<br/>1.202.537.7560
<br/>123456789
<br/>703-356-5300 x2048
<br/>(212) 555-1212
<br/>1 + (212) 555-1212
<br/>1 (292) 226-7000

Open in new window

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37057659
From the look of this question and another one I saw here at EE, I'd like to suggest this little book.  It's very readable and has great examples.
http://www.sitepoint.com/books/phpmysql4/
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

580 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question