title: Adding elements to array as sub-elements dynamically in PHP
body: <p>I want to find a workaround for the following problem:</p>
  <p>I have n vectors(unique), like the following: (&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, ..., &quot;valn&quot; ).
  Each vector's length is different.</p>
  <p>I want to add any of those in a new array, but using the vector values(val1,val2,val3) elements as sub-elements recursively for the new array, taken from the main vector(val1 =&gt; val+1 =&gt; val+2 =&gt; val+3 =&gt; ... val+n =&gt; solution), and the last element of the vector is an integer or a string(not a sub-array/vector as the others), which will match with the last element of the new array, and it's new array's soluton/target.</p>
  <p>The workaround solution I am applying right now is this:
  Let's suppose the target(solution) is the end value of the array(an integer or string).
  In this case I suppose to work on a vector with 4 elements, where the last one is the solution.</p>
  <pre><code>$vector = array(&quot;val1&quot;, &quot;val2&quot;, &quot;val3&quot;, &quot;target&quot;);
  $count = count($vector);
  $new_array = array();
  switch($count){
  case 1:
  ....
  case 4:
  $new_array[$vector[0]][$vector[1]][$vector[2]] = $vector[3];
  /*New array will be
  $new_array = [
  val1 =&gt; 
    val2 =&gt; 
      val3 =&gt; &quot;target&quot;
  ];
  */
  break;
  }
  </code></pre>
  <p>The vectors I am using are many and with different sizes, so the solution/target can be in the 1st element, second, third and so on, so I applied in my switch any cases from 0 to 5 for example, working as wrote above.</p>
  <p>I think there could be a better solution, to loop inside a for(or better, a while) cycle
  But I am currently having no ideas on how it should be, and I didn't find any workaround in the web.</p>
  <p>Does anyone have a soluton for this?
  Thanks in advance</p>