user2816983
user2816983

Reputation:

How I get dynamic name?

Good day.

Me need check 42 names, but it very long:

Useally i use next code:

$info_1 = (isset($info['1'])) ? $info['1'] : 0;
$info_2 = (isset($info['2'])) ? $info['2'] : 0;

$info_42 = (isset($info['42'])) ? $info['42'] : 0;

Can i get dinamic name?

ex. i want use code:

for($i=0;$i<43;$i++){
$info_$i = (isset($info[$i])) ? $info[$i] : 0;
}

How aright add $i for $info?

And is it possible?

Upvotes: 0

Views: 66

Answers (4)

user965306
user965306

Reputation:

for($i=0;$i<43;$i++){
    $name = 'info_'.$i;
    $$name = (isset($info[$i])) ? $info[$i] : 0;
}

Upvotes: 4

Eternal1
Eternal1

Reputation: 5625

You can do it like this

for($i = 0; $i<43; $i++) {
  $var_name = "info_{$i}";
  $$var_name = isset($info[$i])) ? $info[$i] : 0;
}

But if you really need this kind of stuff you're doing it real wrong and better off converting this long list of variables to an array;

Upvotes: 0

bouscher
bouscher

Reputation: 1360

Just another option:

for($i=0;$i<43;$i++){

  ${"info_$i"} = (isset(${"info_$i"}) ? ${"info_$i"} : 0;
}

Upvotes: 0

Adam
Adam

Reputation: 1371

Better use an array:

for($i=0;$i<43;$i++){
    $info[$i] = (isset($info[$i])) ? $info[$i] : 0;
}

Upvotes: 1

Related Questions