Technique for creating variables within a loop

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Dave Monk

    Technique for creating variables within a loop

    Hi,
    I'm reasonably proficient in PHP but have been asked how to do
    something which has got me stumped. Hence, my posting:

    I want to create a small number of variables, $pos1, $pos2 ... $pos5
    within a loop and assign them values from an array, but creating the
    variable names with incrementing numbers, well I've no idea how the PHP
    syntax for it works.


    ========== START CODE ==========
    <?php

    $x=5;
    $myarray = array('a','b',' c','d','e');

    for($a=0;$a<$x; $a++){
    $pos.$a = $myarray[$a]; //Create $pos0 here on first loop,
    // $pos1 next loop and so forth..
    }

    //Test assigned variable
    echo $pos3; // $pos3 should equal 'd'
    exit;

    ?>

    ========== END CODE ==========

    Any ideas?

  • Janwillem Borleffs

    #2
    Re: Technique for creating variables within a loop

    Dave Monk wrote:
    I want to create a small number of variables, $pos1, $pos2 ... $pos5
    within a loop and assign them values from an array, but creating the
    variable names with incrementing numbers, well I've no idea how the
    PHP syntax for it works.
    >
    $pos = 'prefix';
    .....
    ${$pos.$a} = $myarray[$a];


    JW


    Comment

    • Miguel Cruz

      #3
      Re: Technique for creating variables within a loop

      "Dave Monk" <dmonk@supersca pe.comwrote:
      I want to create a small number of variables, $pos1, $pos2 ... $pos5
      within a loop and assign them values from an array, but creating the
      variable names with incrementing numbers, well I've no idea how the PHP
      syntax for it works.
      You can do it the way Janwillem suggests, but I would ask why you want
      to do this. Why not use an array ($pos[1], $pos[2], etc.)? That's what
      they're for.

      miguel
      --
      Photos from 40 countries on 5 continents: http://travel.u.nu
      Latest photos: Malaysia; Thailand; Singapore; Spain; Morocco
      Airports of the world: http://airport.u.nu

      Comment

      Working...