Syntax of variable variables within a for()

Hi there,

I’m new to PHP so please bear with me if I’m asking the obvious.

I want to create an array by looping through using a for(). Each of my array item values shares the same name except for the fact that the numerical character within it increments by 1. My code is below:-


for($x=0;$x<4;$x++)
$abilities[] =  array(
'ability' => ${'node->field_course_class' . $x . '_ability'},
);
}

As you’ll notice the the variable in question is $field_course_class[number]_ability. For each loop I want the value of [number] to increase by one, based on the value of $x in the for() function. I believe that if I was specifically calling the variable on it’s own, then it would work. However, is it possible that the above isn’t working due to the fact that I’m declaring a variable that include it’s parent standard-class object too ($node)?

Ultimately, I want the result to be:-


$abilities = array(
  [0] = array(
    'ability' => $field_course_class0_ability,
  ),
  [1] = array(
   'ability' => $field_course_class1_ability,
  ),
  [2] = array(
   'ability' => $field_course_class2_ability,
  ),
}

When I use the following code,

${'node->field_course_class' . $x+1 . '_ability'}

, it doesn’t invoke any errors but does not work either. I suppose my question is really about how to concatenate a variable variable within it’s parent variable. Could someone give me a pointer as to the correct syntax for this context?

Thanks for you help in advance

Yes, I’ll be adding more items when I have this issue sorted.

Unfortunately, your solution didn’t work. However, upon jiggling it about a bit, I’ve made it work.

Instead of ${“node->field_course_class{$x}_ability”}, I placed the it’s parent object outside of the curly braces like $node->{“field_course_class{$x}_ability”}, and it now works great. Thanks for your suggestion and help :slight_smile:

Not sure why you need an array of arrays for this, but i’m assuming you need to add things to them later on. So…

Try this instead…

‘ability’ => ${“node->field_course_class{$x}_ability”}