mattrweaver
mattrweaver

Reputation: 17

exploded variables in foreach, but after the first array, arrays start at 1 instead of 0

I am taking a list of names and putting the last name first. When I use explode to create the $name array, the first name has the first name in array position 0 and the last name at position 1, but the other names all start with first name at position 1 and last name at position 2.

I copied this code from another script that does similar things, but in that code all of the first names, including the first instance, start at number 1 (at least its consistent).

I'm guessing I'm missing something fundamental. I appreciate your assistance.

The code follows.

$_511a = 'Maria Smith, Lance Farquardt, Daniel Berquist, John Barton, Milo Silver';
echo '511a: ' . $_511a . '<br />';
$castsplit = explode(',' , $_511a);
foreach($castsplit as $cast) {
    $name = explode(' ',$cast);
    $lastname = end($name);
    if(count($name) >= 4){
        $middlename = $name[2];
    } else {
        $middlename = null;   
    }
    $firstname = $name[1];
    if($middlename){
        $castmembers[] = $lastname . ', ' . $firstname .  ' ' . $middlename;
    } else {
        $castmembers[] = $lastname . ', ' . $firstname;
    }
}
echo "Corrected names: <br />";
foreach($castmembers as $castmember) {
    echo $castmember . '<br />';
}

Upvotes: 0

Views: 786

Answers (4)

wassup
wassup

Reputation: 2503

The problem is a space after a comma between names. Either use exclusively "," or ", " as a separator, or use regular expression to split the string.

$castsplit = preg_split('/,\s*/', $_511a);

The above will accept all separators alike to this: <comma><zero or more spaces>.

Upvotes: 2

Tariq Aziz
Tariq Aziz

Reputation: 798

You have spaces in between the string '$_511a' so explode function must have a space also. so the index of $name will also be changed because now we have the first element on 0 index.

change code

$castsplit = explode(',' , $_511a);

to

$castsplit = explode(', ' , $_511a);

and

$firstname = $name[1];

to

$firstname = $name[0];

Upvotes: 0

Jacob
Jacob

Reputation: 1062

try maybe:

$castsplit = explode(", ", $_511a);

//your variable name cast is ambiguous.  I changed it
foreach($castsplit as $member) {
  $nameArr = explode(' ', $member);
  $first = $nameArr[0];
  $last = end($nameArr);
  str_replace($first, $last, $member, 1);
  str_replace($last, $first, $member, 1);

  echo $member;
}

notice the space after the comma in the first explode

Upvotes: 0

Sammitch
Sammitch

Reputation: 32242

After the first name in the list all the names are preceded by a space. explode() counts that space, putting a blank string in the 0 index in the resulting array.

Change:

$name = explode(' ',$cast);

To:

$name = explode(' ',ltrim($cast));

Upvotes: 3

Related Questions