user2178521
user2178521

Reputation: 843

Changing variable's name in loop

I have more than 50 string. I need to put those string into one array. I try to use loop to create it. however I have trouble on auto increment var's name. $string.$s($string1, $string2). It will become Undefined variable, Any way to change var's name?

$string0="ABC";
$string1="DEF";
$string2="GHI";
...


$data=array($string0, $string1, $string2...);

for($s=0; $s<50; $s++){
    $data[$s]=$string.$s;
}

Upvotes: 0

Views: 235

Answers (2)

mpyw
mpyw

Reputation: 5754

Not

$string.$s;

But

${'string'.$s};

Needless to say, the best solution is:

$data = array(
    'ABC',
    'DEF',
    'GHI',
);

or

$data = array();
$data[] = 'ABC';
$data[] = 'DEF';
$data[] = 'GHI';

or

$data = array();
$data[0] = 'ABC';
$data[1] = 'DEF';
$data[2] = 'GHI';

You can also replace them by your editor's function.

I'll take one example, Notepad++. (Japanese plug-in is set on, sorry)

Let's try like this: enter image description here

Points:

  • Search by (\$string)([0-9]+)(=)
  • Replace to \1[\2]\3
  • Mode Regex

Upvotes: 7

Laurent S.
Laurent S.

Reputation: 6947

something like this should work I guess :

for($s=0; $s<50; $s++)
{
    $myvar = "string" . $s;
    $data[$s]=$$myvar;
}

Upvotes: 3

Related Questions