0

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);
  }
}


?>
1
  • try echo $arrayName and echo $$arrayName and see what you get. I bet it's something useless and null like the error message says. Commented Mar 12, 2012 at 19:43

3 Answers 3

6

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);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

i guess the OP constructed this example for us and in reality, he does not have the name of the array (except for the string).
@Kaii possibly. I just hate to see an over-engineered solution. When a simple solution exists, why not just use it?
Why declare $arrayName at all?
3

You get the first warning because your $arrayName variable is not actually an array, you made it into a string.

So instead of:

$arrayName = "word_list[" . $i . "]";

You should have this:

$arrayName = $word_list[$i];

You get your second warning because your first parameter is not an array.

So instead of:

array_push($$arrayName , $word);

You should have this:

array_push($arrayName , $word);

If you make these changes you will get an array that looks like this in the end:

$wordlist = array( array("1", "abc"), array("1", "abc"), ... ); // repeated 23 times

Comments

1

And in the for loop, you are accessing the array the wrong way

Here is your corrected code

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

}

1 Comment

@vaichidrewar, Misunderstood the question, BUT NOW fixed with tested solution

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.