简体   繁体   中英

Can't extract variables from Foreach loop

I have an existing array that I want to extract the first name and last name out separately from a single full name field from and put each into their own variable. I've got the extraction to work the way I need, but I can't seem to retrieve the data once I'm out of the 'foreach' loop.

My array is this..

Array
(
    [0] => 2
    [1] => dduck
    [2] => Donald Duck
    [3] => donald@domain.com
)

When I run the foreach loop (below) the echo works. But if I echo the $firstName and $lastName outside of the loop, nothing is displayed....

This displays first and last name

foreach ($t_result as $name)
{
    preg_match('#^(\w+\.)?\s*([\'\’\w]+)\s+([\'\’\w]+)\s*(\w+\.?)?$#', $name, $results);
    $firstName = $results[2];
    $lastname = $results[3];
    echo $firstName . " " . $lastname;
}

This displays nothing

foreach ($t_result as $name)
{
    preg_match('#^(\w+\.)?\s*([\'\’\w]+)\s+([\'\’\w]+)\s*(\w+\.?)?$#', $name, $results);
    $firstName = $results[2];
    $lastname = $results[3];
}
echo $firstName . " " . $lastname;

Any ideas?

You are not checking whether or not there is a match on your regex so for the array elements that do not match you are assigning $firstName and $lastname to undefined indexes.

The example array will not match on element [3] so those variables are more or less empty at the end of the loop making your echo outside of the loop not display anything.

You can try something like the following (wrapping the preg_match in an if statement):

foreach ($t_result as $name)
{
    if (preg_match("#^(\w+\.)?\s*(['\’\w]+)\s+(['\’\w]+)\s*(\w+\.?)?$#", $name, $results)) {
       $firstName = $results[2];
       $lastname = $results[3];
    }
}
echo $firstName . " " . $lastname;

You need to wrap the variables you're tring to return in an 'if' statement, otherwise the values are overwritten by subsequent loops:

$t_result = array(
    0 => 2,
    1 => 'dduck',
    2 => 'Donald Duck',
    3 => 'donald@domain.com',
);

foreach ( $t_result as $name ) {
    if ( preg_match( '#^(\w+\.)?\s*([\'\’\w]+)\s+([\'\’\w]+)\s*(\w+\.?)?$#', $name, $results ) ) {
        $firstName = $results[2];
        $lastname = $results[3];
    }
}

echo $firstName . " " . $lastname;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM