Q:

Using str_replace with array gives unexpected results

I have an array of IDs stored in a database, something like 1,2,3,4,5,6,7, etc.
I have a group of labels I am trying to apply to these numbers for use later on, but my output isn't showing what I expect.  For instance, I have this:
$ids[0] = 7, $ids[1] = 4

I use this to apply the labels:
$ids = str_replace('7', '1Mbps Internet', $ids);
$ids = str_replace('4', '2Mbps Internet', $ids);
$ids = str_replace('1', '3Mbps Internet', $ids);
$ids = str_replace('8', 'Commercial Internet', $ids);
$ids = str_replace('12', 'Tower Friends', $ids);
$ids = str_replace('6', 'Cable TV', $ids);
$ids = str_replace('11', 'Cable TV Basic', $ids);
$ids = str_replace('5', 'VOIP', $ids);
$ids = str_replace('10', 'Web Services', $ids);

However, my output is looking like this:
3Mbps InternetMbps Internet, 2Mbps Internet

When it should come out like this:
1Mbps Internet, 2Mbps Internet

$Package1 = $ids[0]; 
$Package2 = $ids[1];
$Package3 = $ids[2];
$Package4 = $ids[3];

if (!$Package1) {$P_word = "$Package:"; $Packages = "None Subscribed";}
else if ($Package1 && !$Package2) {$P_Word = "Package:"; $Packages = "$Package1";}
else if ($Package1 && $Package2 && !$Package3) {$P_Word = "Packages:"; $Packages = "$Package1, $Package2";}
else if ($Package1 && $Package2 && $Package3 && !$Package4) {$P_Word = "Packages:"; $Packages = "$Package1, $Package2, $Package3"; }
else {$P_Word = "Packages:"; $Packages = "$Package1, $Package2, $Package3, $Package4"; }

A:

str_replace() is a basic search. Part of your issue is how you expect PHP to search your string. For example,
$ids = str_replace('7', '1Mbps Internet', $ids);
$ids = str_replace('4', '2Mbps Internet', $ids);
$ids = str_replace('1', '3Mbps Internet', $ids);

On the 3rd line, you are searching for the string "1". Since your first call replaced "7" with "1Mbps...", the 3rd line will replace the "1" in that sentence as well. I would recommend iterating over the array, or use some regex. One approach would be:
$new_data = array();

foreach( $ids as $id ) {
    switch( $id ) {
        case 1:
            $new_data[] = '3Mbps Internet';
            break;
        case 7:
            $new_data[] = '1Mbps Internet';
            break;
    }
}

//remove duplicates?
$new_data = array_unique($new_data);

Partial implementation, but hopefully you get the point.

