Concatenate string and variable to make up a constant name

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

    Concatenate string and variable to make up a constant name

    Hi,

    I know that it is possible to build up a variable name based on a
    string and another variable name i.e.

    $varnum=5;
    ${"varnumber_$v arnum"} = 'This variable should be called varnumber_5';

    but is it possible to do this for a constant? For example I may have
    constants set up as

    define('CONSTNU MBER_1', 'This is constantnumber 1');
    define('CONSTNU MBER_2', 'This is constantnumber 2');
    define('CONSTNU MBER_3', 'This is constantnumber 3');

    and I may want to access them from inside a loop i.e.

    for($counter=1; $counter<=3; $counter}}) {
    echo 'Contents of current constant = ' . ${"CONSTNUMBER_ $counter"} ;
    }

    Now obviously this doesn't work because it sees
    ${"CONSTNUMBER_ $counter"} as a variable but if I try and take the $
    off then I just get errors.

    Can anyone help? Does this even make sense? :-)

  • Peter

    #2
    Re: Concatenate string and variable to make up a constant name


    Peter wrote:
    Hi,
    >
    I know that it is possible to build up a variable name based on a
    string and another variable name i.e.
    >
    $varnum=5;
    ${"varnumber_$v arnum"} = 'This variable should be called varnumber_5';
    >
    but is it possible to do this for a constant? For example I may have
    constants set up as
    >
    define('CONSTNU MBER_1', 'This is constantnumber 1');
    define('CONSTNU MBER_2', 'This is constantnumber 2');
    define('CONSTNU MBER_3', 'This is constantnumber 3');
    >
    and I may want to access them from inside a loop i.e.
    >
    for($counter=1; $counter<=3; $counter}}) {
    echo 'Contents of current constant = ' . ${"CONSTNUMBER_ $counter"} ;
    }
    >
    Now obviously this doesn't work because it sees
    ${"CONSTNUMBER_ $counter"} as a variable but if I try and take the $
    off then I just get errors.
    >
    Can anyone help? Does this even make sense? :-)
    Typically I've just found the answer. I just build up a string of the
    constant name and then wrap the constant function around it.

    Obviously I was overcomplicatin g things. Ah well.

    Comment

    Working...