0

I create a $values array and then extract the elements into local scope.

 $values['status'.$i] = $newStatus[$i];
 extract($values);

When I render an html page. I'm using the following

 <?php if(${'status'.$i} == 'OUT'){ ?>

but am confused by what the ${ is doing and why $status.$i won't resolve

1
  • This is a "variable variable" Commented Oct 13, 2016 at 20:34

2 Answers 2

4

$status.$i means

take value of $status variable and concatenate it with value of $i variable.

${'status'.$i} means

take value of $i variable, append id to 'status' string and take value of a variable 'status'.$i

Example:

With $i equals '2' and $status equals 'someStatus':

  • $status.$i evaluated to 'someStatus' . '2', which is 'someStatus2'

  • ${'status'.$i} evaluated to ${'status'.'2'} which is $status2. And if $status2 is defined variable - you will get some value.

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

Comments

1

I wanted to add to the accepted answer with a suggested alternate way of achieving your goal.

Re-iterating the accepted answer...

Let's assume the following,

$status1 = 'A status';
$status = 'foo';
$i = 1;
$var_name = 'status1';

and then,

echo $status1; // A status
echo $status.$i; // foo1
echo ${'status'.$i}; // A status
echo ${"status$i"}; // A status
echo ${$var_name}; // A status

The string inside the curly brackets is resolved first, effectively resulting in ${'status1'} which is the same as $status1. This is a variable variable.

Read about variable variables - http://php.net/manual/en/language.variables.variable.php

An alternative solution

Multidimensional arrays are probably an easier way to manage your data.

For example, instead of somthing like

$values['status'.$i] = $newStatus[$i];

how about

$values['status'][$i] = $newStatus[$i];

Now we can use the data like,

extract($values);

if($status[$i] == 'OUT'){ 
   // do stuff
}

An alternative solution PLUS

You may even find that you can prepare your status array differently. I'm assuming you're using some sort of loop? If so, these are both equivalent,

for ($i=0; $i<count($newStatus); $i++){
    $values['status'][$i] = $newStatus[$i];
}

and,

$values['status'] = $newStatus;

:)

Comments

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.