-1

Say I have this PHP array()

$tour_from array

Array
(
    [0] => Array
        (
            [0] => Dhaka
            [1] => noakhali
        )

    [1] => Array
        (
            [0] => Chittagong
            [1] => Sylhet
        )

)

I want to make like this:

Dhaka - Noakhali
Chittagong - Sylhet

How can I do this?

I used this but it's the wrong way:

foreach ($tour_from as $key => $value) {
    $chunk = array_chunk($value, 2);
    foreach ($chunk as $key1 => $value1) {
       echo $value1[$key][$key1] . ' - ' . $chunk[$key][$key1];
       echo '<br/>';
    }
 }

4 Answers 4

2

I think you're overcomplicating it a bit. Why not just loop over the outer array and implode the inner array?

<?php

$tour_from = [
    ['Dhaka', 'Noakhali'],
    ['Chittagong', 'Sylhet'],
];

foreach ($tour_from as $elem) {
    print implode(' - ', $elem);
    print '<br>';
}
Sign up to request clarification or add additional context in comments.

Comments

2

There is no need for chunking or a second loop.

One loop containing implode() will do.

Code: (Demo)

$tour_from = [
    ['Dhaka', 'Noakhali'],
    ['Chittagong', 'Sylhet']
];

foreach ($tour_from as $row) {
    echo implode(' - ', $row), "\n";
}

Output:

Dhaka - Noakhali
Chittagong - Sylhet

Alternatively, if you like a functional one-liner: (Demo)

echo implode("<br>", array_map(function($row){ return implode(' - ', $row); }, $tour_from));

*The advantage to this is there is no trailing <br> on the final imploded string.


Or with fewer function calls, here is a version with array_reduce(): (Demo)

echo array_reduce($tour_from, function($carry, $row) {
    return $carry .= ($carry !== null ? "<br>\n" : '') . $row[0] . ' - ' . $row[1];
});

2 Comments

Bro you're in my head.
Yes, but I'd say it shouldn't. Well done seeing that and testing it out both ways. PHP functions... they always have little surprises.
1

If you want to avoid using foreach you can do the same thing with array_walk and pass by reference &$var.

$array = [
    ["Dhaka", "noakhali"],
    ["Chittagong", "Sylhet"]
];

array_walk($array, function(&$item){
    $item = implode(' - ', $item);
});

print_r($array);

Output:

 Array
(
    [0] => Dhaka - noakhali
    [1] => Chittagong - Sylhet
)

Sandbox

If you want to output it instead of modify the array you can just echo it instead or do something like implode('<br>', $array) afterwords.

Comments

-2

OH, Yes, I found the way:

foreach ($tour_from as $key => $value) {
    $chunk = array_chunk($value, 2);
    foreach ($chunk as $key1 => $value1) {
       echo implode(' - ', $value1);
       echo '<br/>';                                                  
    }
 }

Comments

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.