Mati
Mati

Reputation: 11

Combine two arrays into a string

I need to create a new array called ar1 with the items: [Dublin, Budapest, Copenhagen] and ar2 with [Ireland, Hungary, Denmark] after than answer with a string containing each country from the countries-array followed by the corresponding capital. Use the format "country = capital, * country = capital..."

Check code below but i know that is another way to doing that ex. For loop but can someone explain me how?

$ar1 = ["Dublin", "Budapest", "Copenhagen"];
$ar2 = ["Ireland", "Hungary", "Denmark"];
$ANSWER = $ar2[0] . " = " . $ar1[0] . ", " . $ar2[1] . " = " . $ar1[1]. ", " . $ar2[2] . " = " . $ar1[2];

Upvotes: 1

Views: 63

Answers (4)

iainn
iainn

Reputation: 17417

If you've got two related lists in separate variables, it's often easier to transpose them into a single structure first. In PHP, you can do this like so:

$transposed = array_map(null, $ar1, $ar2);

Once they're combined, it's a lot more simple to generate the required output:

echo implode(', ', array_map(function($row) {
    return "{$row[1]} = {$row[0]}";
}, $transposed));

Ireland = Dublin, Hungary = Budapest, Denmark = Copenhagen

See https://3v4l.org/LfvIY

Upvotes: 0

Elementary
Elementary

Reputation: 1453

More fast and simple way:

$countries=["Ireland", "Hungary", "Denmark"];
 $capitals=["Dublin", "Budapest", "Copenhagen"];
 $string=implode(',',array_map(function($country,$capital){ return "$country=$capital";},$countries,$capitals));
 var_dump($string);

output:

string(50) "Ireland=Dublin,Hungary=Budapest,Denmark=Copenhagen"

Upvotes: 0

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

Another way to do it using array_combine()

<?php
$ar1 = ["Dublin", "Budapest", "Copenhagen"];
$ar2 = ["Ireland", "Hungary", "Denmark"];
$result = array_combine($ar2,$ar1);

$ANSWER = '';
$i = 0;
$comma = ', ';
$len = count($result);
foreach($result as $country => $capital) {
    if ($i == $len - 1){
        $comma='';
    }
    $ANSWER .= $country . ' = ' . $capital.$comma;
    $i++;
}

echo $ANSWER;

DEMO: https://3v4l.org/WGtJ3

Using array_map()

$ar1 = ["Dublin", "Budapest", "Copenhagen"];
$ar2 = ["Ireland", "Hungary", "Denmark"];
$input = array_combine($ar2,$ar1);
$output = implode(', ', array_map(
    function ($v, $k) { return sprintf("%s=%s", $k, $v); },
    $input,
    array_keys($input)
));

echo $output;

DEMO: https://3v4l.org/qps1G

Upvotes: 1

user3783243
user3783243

Reputation: 5224

You should use a foreach and the key.

$ar1 = ["Dublin", "Budapest", "Copenhagen"];
$ar2 = ["Ireland", "Hungary", "Denmark"];
$ANSWER = '';
foreach($ar1 as $key => $capital) {
    $ANSWER .= $ar2[$key] . ' = ' . $capital . ', ';
}
echo rtrim($ANSWER, ', ');

... and then rtrim to remove the last ,.

https://3v4l.org/f8PJN

Upvotes: 2

Related Questions