1

I have 3 explode statements:

$emails = explode(',', $row['email']);
$firstnames = explode(',', $row['first_name']);
$lastnames = explode(',', $row['last_name']);

each explode produces three (3) arrays:

//emails
Array
(
    [0] => [email protected]
    [1] => [email protected]
    [2] => [email protected]
    [3] => [email protected]
)

//first name
Array
(
    [0] => Bill
    [1] => Jake
    [2] => John
    [3] => Bob
)

//last name
Array
(
    [0] => Jones
    [1] => Smith
    [2] => Johnson
    [3] => Bakers
)

I can get the one array easily like this: for example:

foreach ($emails as $email) {
    echo $email;
}

That will echo out the emails. But I want to add $firstname and $lastname into it. for example, I want to echo:

[email protected] Bill Jones

how can i do it?

1 Answer 1

2

foreach can assign a key and value if you use the appropriate syntax:

foreach ($emails as $key => $email) {
    echo $email;
    echo $firstnames[$key];
    echo $lastnames[$key];
}

Next time, consult the manual: http://php.net/manual/en/control-structures.foreach.php as this is shown at the very top.

As Pyromonk pointed out, for is useful in situations where you have indexed arrays:

for ($i = 0, $n = count($emails); $i < $n; $i++) {
    echo $emails[$i];
    echo $firstnames[$i];
    echo $lastnames[$i];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively, a for loop could be used instead of foreach, as it would make more sense in this context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.