0

I dont know if this is possible but can you create a variable loop?

I want to create many variables in an if condition

if($session[hello]){
$array1 = array("");
$array2 = array("");
$array3 = array("");
$array4 = array("");
$array5 = array("");
}

but since I have more I want to write it like this:

 if($session[hello]){
for($a = 1; $a <= 5; $a++){
$array + $a = array("");
}

But its not working and I cant figure out how this might be possible.

is there an alternative?

thanks

5
  • php.net/manual/en/language.variables.variable.php Commented Oct 27, 2015 at 12:36
  • What is the expected output? Commented Oct 27, 2015 at 12:36
  • What do you want to achieve? Do you want the previous array to be appended to the next? Commented Oct 27, 2015 at 12:36
  • the expected output is when the original variables are used else where in the code, they dont produce errors when some of them are missing... if that makes sense Commented Oct 27, 2015 at 12:40
  • "the expected output is when the original variables are used else where in the code, they dont produce errors when some of them are missing". Where is "elsewhere"? Inside a function? Otherwise, @b0s3's answer should be what you need. Commented Oct 27, 2015 at 12:45

1 Answer 1

2

You can try this -

if($session[hello]){
  for($a = 1; $a <= 5; $a++){
     ${'array' . $a} = array("");
  }
}

Don't why you want it this way but using an array would be better.

if($session[hello]){
  for($a = 1; $a <= 5; $a++){
     $array[$a] = array("");
  }
}

And access it like $array[1] or $array[2] etc.

Sign up to request clarification or add additional context in comments.

4 Comments

hi, thanks for the suggestions. maybe it would help if I explain the whole reason why I am doing it. I have a whole bunch of data from database that I want to echo out from an array in the code. and my solution to "null" data that would give me 'undefined offset' errors is to create a condition that if they dont exist, to turn that variable into an empty array instead of an null object. am I just going about it all wrong?
Yes you're probably doing it wrong, you should just check if the variable is set using php.net/isset
Why not simply use isset or empty accordingly?
yes! i just looked it up and empty is what i needed. ty

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.