Skip to content
Advertisement

How to create arrays for each values – PHP

// ARRAY
(
    [apple] => one
    [orange] => two
    [strawberry] => three
)

// NEW ARRAY
(
    [0] => Array
        (
            [0] => apple
            [1] => one
        )

    [1] => Array
        (
            [0] => orange 
            [1] => two
        )

    [2] => Array
        (
            [0] => strawberry
            [1] => three
        )

)

I want to create an array for each key of the current array, so i can use this in a foreach later. Is it possible?

I’ve tried everything without success.

Advertisement

Answer

You can loop through every elements in your associative array and create an empty array before the loop. Then push the key as well as value to the new array. This way you can get that desirable output:

<?php

$assocArray = [
    "apple" => "one",
    "orange" => "two",
    "strawberry" => "three"
];

echo "Before: nr";
print_r($assocArray);

$newArray = [];

foreach ($assocArray as $key => $item) {
    $newArray[] = [$key, $item];
}

echo "After: nr";
print_r($newArray);

Output

Before: 
Array
(
    [apple] => one
    [orange] => two
    [strawberry] => three
)
After: 
Array
(
    [0] => Array
        (
            [0] => apple
            [1] => one
        )

    [1] => Array
        (
            [0] => orange
            [1] => two
        )

    [2] => Array
        (
            [0] => strawberry
            [1] => three
        )

)
``
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement