I have a foreach loop, within which I would like to create x number of unique variables.

E.g. Upon each iteration I'd like to create a new variable like:

$strDisk1 = ...
$strDisk2 = ...
$strDisk3 = ...

I have tried the following but this does not work:

<?php
$count=1;
foreach ($disk as $device)
{
    $strDisk.$count = "<dataset seriesName='$device'>";
    $count++;
}
?>

Is there something which will enable me to do this?

Recommended Answers

All 4 Replies

I know there's a way that you can dynamically declare variable names, but I'm not exactly sure what the syntax looks like, so I'll let someone else chime in with that. In the mean time, could you use an array?

$count=1;
$strDisk = array();
foreach ($disk as $device)
{
    $strDisk[$count] = "<dataset seriesName='$device'>";
    $count++;
}
<?php

$count=1;

$disk = array(
    'test1',
    'test2',
    'test3',
);

foreach ($disk as $device)
{
    $var = 'strDisk'.$count;
    $$var = "<dataset seriesName='$device'>";
    $count++;
}

var_dump( get_defined_vars() );

if you look through the variable output you should see:

'strDisk1' => string '<dataset seriesName='test1'>' (length=28)
      'strDisk2' => string '<dataset seriesName='test2'>' (length=28)
      'strDisk3' => string '<dataset seriesName='test3'>' (length=28)

*Note* var_dump output is formatted by the xdebug plugin.

Ah yes, I just found the 'variable variables' man page. I shall try and implement this properly tomorrow.
Many thanks
ns

I see you already mentioned variable variables. I've used these a few times, like so:

<?php
$count = 0;
foreach($array as $k => $v){
$count++;
$var = "info".$count;
$$var = $v;
}

echo $info1."<br />";
echo $info2."<br />";
echo $info3."<br />";
echo $info4."<br />";
echo $info5."<br />";
echo $info6."<br />";
//...
?>

But from the look your code, I would use arrays. Variable Variables can be complicated and you can set variables and not keep track of them and can cause problems further on down the road. Once I used variable variables to make a php based web ring work properly, but arrays are much better because you can keep track of them from a single variable name.

I do like this idea more though:

<?php


$array = array('0' => 'This','1' => 'Is','2' => 'Sparta');

$count = 0;

foreach($array as $k => $v){
$count++;
$new_data["name".$count] = $v;
}

extract($new_data);

echo $name1."<br />";
echo $name2."<br />";
echo $name3."<br />";
//...

?>

Good Luck

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.