0

If I have this array in PHP:

array(3) {
  [0]=>
  string(5) "first"
  [1]=>
  string(6) "second"
  [2]=>
  string(5) "third"
}

How can I convert this single array into a multidimensional array? What is the quickest way? So I can access this array like:

$array["first"]["second"]...

I want to be able to then set a value to this index like:

$array["first"]["second"]["third"] = "example";

I thought that I need a for loop or a recursive function but I have no idea how to start.

6
  • 3
    Not really clear what the end result should look like. In your example, you've changed the values into the indexes. e.g. if you echo $array["first"]["second"];, what should it output? What value should be in that field? Commented Mar 30, 2020 at 15:22
  • 1
    Also...what have you researched or tried so far? We generally prefer to help people with their existing code, rather than just provide the whole solution on a plate. It's better to show you've at least attempted to solve the problem. Commented Mar 30, 2020 at 15:23
  • @ADyson Sorry that my question is not clear, I thought that I need a for loop or a recursive function but I have no idea how to start. I have updated my question a little to state how I wish to assign a value to the index. Commented Mar 30, 2020 at 16:38
  • 1
    Thanks. I can't answer properly now as the question is closed, but here you go: sandbox.onlinephpfunctions.com/code/… . It wasn't quite as simple as I had imagined to begin with. The key to it was doing the process backwards - starting with the last array and then wrapping it in more arrays until you get back to the top level. Commented Mar 30, 2020 at 21:53
  • @ADyson Thank you! I would accept your answer if I could. Commented Mar 31, 2020 at 10:40

1 Answer 1

1

It wasn't quite as simple as I had imagined to begin with. The key to it was doing the process backwards - starting with the last array and then wrapping it in more arrays until you get back to the top level.

$array = array("first", "second", "third");
$newArr = array();

//loop backwards from the last element
for ($i = count($array)-1; $i >= 0 ; $i--)
{
    $arr = array();
    if ($i == count($array)-1) {
        $val = "example";
        $arr[$array[$i]] = $val;
    }
    else { 
        $arr[$array[$i]] = $newArr;
    }
    $newArr = $arr;
}

var_dump($newArr);
echo "-------".PHP_EOL;
echo $newArr["first"]["second"]["third"];

Demo: http://sandbox.onlinephpfunctions.com/code/0d7fa30fde7126160fbcc0e80e5727f17b19e39f

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.