0

I think I am just plain stupid but I can't seem to get this to go. I have a string which I subsequently turn into an array

$string = "apple;pears;bananas";
$array = explode(";", $string);

The values of $array each need to be in its own array with the following base structure:

$basearray = array(
    "label" => "",
    "value" => "",
    );

ultimately yielding an array of three arrays , where label and value of the first array are both "apples", "pears" for the second array etc. The trick is that the initial string might be longer/shorter (say "apple;pears;bananas;kiwis;strawberries"; and should thus yield a different amount of arrays. I hope I make myself clear enough :)

1 Answer 1

1

That is a use case for array_map:

$string = 'apple;pears;bananas';
$array = explode(';', $string);

$result = array_map(fn($item) => [ 'label' => $item, 'value' => $item], $array);

print_r($result);

Output:

Array
(
    [0] => Array
        (
            [label] => apple
            [value] => apple
        )

    [1] => Array
        (
            [label] => pears
            [value] => pears
        )

    [2] => Array
        (
            [label] => bananas
            [value] => bananas
        )

)
Sign up to request clarification or add additional context in comments.

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.