1

Is it possible to use php variable as a part of an array name. like this my arrays are Fday1, Fday2....but i cant go with the foreach keys beacause there are different counts of values for each array

$FdayArray = "Fday".$FdayKey;
array_push($FdayArray, $forecast);

the FdayKey would be a number between 1-9 How do I do this correctly?

3
  • What you expecting result? Commented Oct 5, 2018 at 6:59
  • Can you explain your problem further? What is $forecast? Is there any reason not to use $$FdayArray? Commented Oct 5, 2018 at 6:59
  • Why not use one array to wrap around all your arrays? That way it will all be contained inside a coutable and loopable array that will surely be easier than a dynamic number of arrays Commented Oct 5, 2018 at 7:17

2 Answers 2

2

You are looking for the variable variables feature of php.

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically. It takes the value of a variable and treats that as the name of a variable

You would use

array_push($$FdayArray, $forecast);
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of maintaining different array for each $FdayKey, you can have an associative array, which has internal arrays corresponds to each $FdayKey

The array can look like:

$FdayArray = [
  '1' => [],
  '2' => [],
  '3' => [],
  '4' => [],
  '5' => [],
  '6' => [],
  '7' => [],
  '8' => [],
  '9' => []
];

When you need to push to the array, just use the $FdayKey as a index to get the relevant array.

So you can push as:

array_push($FdayArray[$FdayKey], $forecast);

2 Comments

This is a better option. I understand what you mean but maybe you can make it more clear for OP what you mean?
Good one! I have already upvoted. But if I could I would do it again!

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.