9

Trying to use the implode() function to add a string at the end of each element.

$array = array('9898549130', '9898549131', '9898549132');
$attUsers = implode("@txt.att.net,", $array);

print($attUsers);

Prints this:

9898549130@txt.att.net,9898549131@txt.att.net,9898549132

How do I get implode() to also append the glue for the last element?

Expected output:

9898549130@txt.att.net,9898549131@txt.att.net,9898549132@txt.att.net
                                                      //^^^^^^^^^^^^ See here
Rizier123
  • 58,877
  • 16
  • 101
  • 156
Ryan Litwiller
  • 497
  • 5
  • 24

6 Answers6

8

There is a simpler, better, more efficient way to achieve this using array_map and a lambda function:

$numbers = ['9898549130', '9898549131', '9898549132'];

$attUsers = implode(
    ',',
    array_map(
        function($number) {
            return($number . '@txt.att.net');
        },
        $numbers
    )
);

print_r($attUsers);
aalaap
  • 4,145
  • 5
  • 52
  • 59
2

This seems to work, not sure its the best way to do it:

$array = array('9898549130', '9898549131', '9898549132');
$attUsers = implode("@txt.att.net,", $array) . "@txt.att.net";
print($attUsers);
Ryan Litwiller
  • 497
  • 5
  • 24
  • I think it is as good as you can get. Another way would be to append the string to each element and then imploding the array by a comma. – Rizier123 Sep 01 '15 at 17:24
2

Append an empty string to your array before imploding.
But then we have another problem, a trailing comma at the end.
So, remove it.

Input:

$array = array('9898549130', '9898549131', '9898549132', '');
$attUsers = implode("@txt.att.net,", $array);
$attUsers = rtrim($attUsers, ",")

Output:

9898549130@txt.att.net,9898549131@txt.att.net,9898549132@txt.att.net
Community
  • 1
  • 1
Khalil Fazal
  • 41
  • 2
  • 4
1

This was an answer from my friend that seemed to provide the simplest solution using a foreach.

$array = array ('1112223333', '4445556666', '7778889999');

// Loop over array and add "@att.com" to the end of the phone numbers
foreach ($array as $index => &$phone_number) {
    $array[$index] = $phone_number . '@att.com';
}

// join array with a comma
$attusers = implode(',',$array);  

print($attusers); 
Ryan Litwiller
  • 497
  • 5
  • 24
0
$result = '';
foreach($array as $a) {
    $result = $result . $a . '@txt.att.net,';
}
$result = trim($result,',');
-1

There is a simple solution to achieve this :

$i = 1;
$c = count($array);

foreach ($array as $key => $val) {
    if ($i++ == $c) {
        $array[$key] .= '@txt.att.net';
    }
}
Happy Coding
  • 2,517
  • 1
  • 13
  • 24