Search code examples
phparraysdynamic-arrays

dynamically creating array in php


I am trying to create arrays dynamically and then populate them by constructing array Names using variable but I am getting the following warnings

Warning: in_array() expects parameter 2 to be array, null given Warning: array_push() expects parameter 1 to be array, null given

For single array this method worked but for array of arrays this is not working. How should this be done?

<?php

for ($i = 1; $i <= 23; ++$i) 
{
        $word_list[$i] = array("1"); 
}


for ($i = 1; $i <= 23; ++$i) 
{
  $word = "abc";
  $arrayName = "word_list[" . $i . "]";
  if(!in_array($word, ${$arrayName})) 
  {
    array_push($$arrayName , $word);
  }
}


?>

Solution

  • Why are even trying to put array name in a variable and then de-reference that name? Why not just do this:

    for ($i = 1; $i <= 23; ++$i) 
    {
      $word = "abc";
      $arrayName = "word_list[" . $i . "]";
      if(!in_array($word, $word_list[$i])) 
      {
        array_push($word_list[$i] , $word);
      }
    }