marcnyc marcnyc - 1 year ago 61
PHP Question

removing "The " from array values to order alphabetically

I have an array in which every value starts with a name of a venue. Some venues have a "The " in front of them which I want to remove so that when I

the array I don't end up with all the "The ..." venues at the "T".

I wrote this:

function remove_The($array) {
global $all_venue_listings;
// remove the "The" from the listings...
foreach($all_venue_listings as $v) {
if ( substr($v, 0, 4) === "The " || substr($v, 0, 4) === "the " || substr($v, 0, 4) === "THE " ) {
$v = preg_replace("/The /i","",$v);
return $all_venue_listings;

But that doesn't seem to put the changed values back into the array. How can I operate on the array in the
loop so that what I change goes back into the original array?

I tried replacing the
line with this:

$all_venue_listings[] = preg_replace("/The /i","",$v);

But that just creates a duplicate entry in the array (one with "The " and one without).

Answer Source

Two options.

1) Use a reference and update the element directly (note the &):

foreach($all_venue_listings as &$v) {
$v = ...

2) Use a key and update the original array:

foreach($all_venue_listings as $key => $v) {
$all_venue_listings[$key] = ...

Either will work. I prefer #1

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download