Eun
Eun

Reputation: 35

Array's key and value into a string

I'm currently new to coding and I'm trying to complete an exercise I have. I've tried to figure this out on my own, for hours now and for the life of me I can't seem to get it right... Here is the question:

''Create an array with the keys: "one", "two", "three", "four" and "five" and the values: 1, 2, 3, 4, 5. Use a foreach-loop to add all keys and values to an array in the format: ["key"=value, "key"=value, etc]. Use implode() to make the answer a string with all items separated by a comma ,.''

The code I have written is as follows:

$words = ["one", "two", "three", "four", "five"];
$numbas = [1, 2, 3, 4, 5];

$combined = array_combine($words, $numbas);

foreach ($combined as $key => $value) {
    $forimplode = "$key = $value";
}

$imploded = implode(",", $forimplode);

$ANSWER = $imploded;

To me, this looks perfectly fine, but Yeah, I don't know what is going wrong. I really don't.. Haha.. I appreciate all help I'll be given and I'll sure to learn from my mistakes.

Upvotes: 1

Views: 90

Answers (2)

u_mulder
u_mulder

Reputation: 54796

To me, this looks perfectly fine

And to me - not. Because every iteration of foreach overwrites $forimplode with a new string value. Instead, $forimplode should be declared as array and on each iteration new string should be add as a new item to $forimplode:

$forimplode = array();
foreach ($combined as $key => $value) {
    $forimplode[] = "$key = $value";
}

$imploded = implode(",", $forimplode);

Upvotes: 2

Blaise
Blaise

Reputation: 340

You are redeclaring your array every single time the for loop runs. Try this:

$forimplode = array();
foreach ($combined as $key => $value) {
        $forimplode[] = "$key = $value";
    }

Upvotes: 1

Related Questions