0

I have the following code:

$extraPhoto_1 = get_field('extra_photo_1');
$extraPhoto_2 = get_field('extra_photo_2');
$extraPhoto_3 = get_field('extra_photo_3');
$extraPhoto_4 = get_field('extra_photo_4');

But I would like to rewrite it with a for loop, but I can't figure out how to put a variable within the value field. What I have so far is:

  for($i = 1; $i < 5; $i++) {
            ${'extraPhoto_' . $i} = get_field('extra_photo_ . $i');
      }

I've tried with an array like this:

    $myfiles = array();

      for ($i = 1; $i < 5; $i++) {
        $myfiles["$extraPhoto_$i"] = get_field('extra_photo_ . $i');
      }

Nothing seems to fix my problem. I'v searched on the PHP website (variable variable).

3 Answers3

0

There is some bug in your code which not allowing. Use 'extra_photo_'. $i instead of 'extra_photo_. $i'

for($i = 1; $i < 5; $i++) {
            $extraPhoto_.$i = get_field('extra_photo_'. $i);
      }
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
Ajay
  • 235
  • 2
  • 8
0

You can build an array as defined below and than just call extract($myfiles) to access them as variables.

Again your syntax for the get field is incorrect you should append $i after the quotes.

$myfiles = array();

  for ($i = 1; $i < 5; $i++) {
    $myfiles["extraPhoto_".$i] = get_field('extra_photo_'.$i);
  }
extract($myfiles);
Indrajit
  • 405
  • 4
  • 12
0

If you want to create dynamic variable, use below code

for ($i = 1; $i < 5; $i++) {
     ${'extraPhoto_'.$i} = $_POST['extra_photo_'.$i];
 }

if you want to assign variables to array use below code.

for ($i = 1; $i < 5; $i++) {
    $myfiles["extraPhoto_$i"] = $_POST['extra_photo_'.$i];
    /// $myfiles["extraPhoto_$i"] = get_field('extra_photo_'.$i);
  }

and than to see if values are assign to new array or not, you can use below code.

echo "<pre>";print_r($myfiles);echo "</pre>";
Rima
  • 81
  • 3