0

i try with success when combine 2 array into one foreach loop ..

<?php
//var
$phone_prefix_array = $_POST['phone_prefix']; //prefix eg. 60 (for country code)
$phone_num_array    = $_POST['phone'];
$c_name_array       = $_POST['customer_name'];

foreach (array_combine($phone_prefix_array, $phone_num_array) as $phone_prefix => $phone_num) { //combine prefix array and phone number array
    $phone_var = $phone_prefix . $phone_num;
    $phone     = '6' . $phone_var;

    if ($phone_prefix == true && $phone_num == true) { //filter if no prefix number dont show

        echo $phone;
        //customer_name_here

    } else {
  }

}
?>

The result should be like this :

60125487541 Jake
60355485541 Kane
60315488745 Ray
63222522125 Josh

but now im not sure how to combine another array $c_name_array into foreach lopp

PHP version : 5.2.17

3
  • Why not use just a for loop? Commented Feb 6, 2013 at 8:18
  • From the code posted it is not clear what your intention for the third array is. Could you elaborate? Commented Feb 6, 2013 at 8:20
  • It's not very clear on how do you want to combine all three arrays, can you post some sample data, and what you expect as result in your question? Commented Feb 6, 2013 at 8:22

1 Answer 1

3

array_combine is a terrible workaround for your case and will not work if any value in the first array is not a valid key (i.e. not int or string)

PHP 5.3+ has a MultipleIterator for this:

$iterator = new MultipleIterator();
$iterator->attachIterator(new ArrayIterator($phone_prefix_array));
$iterator->attachIterator(new ArrayIterator($phone_num_array));
foreach ($iterator as $current) {
    $phone_prefix = $current[0];
    $phone_num = $current[1];
    // ...
}

Since PHP 5.4 you can write the loop more concise:

foreach ($iterator as list($phone_prefix, $phone_num)) {
    // ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

but my php version is 5.2.17
Any chance to fix that? Support for PHP 5.2 has expired since Jan 2011, so there are no security fixes anymore for over two years.

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.