Reputation: 13
I was wondering if there was a way that I can declare a variable at the top of my php file that contains some 'array stuff' and have it used in a foreach loop below somewhere? For example:
$variable = 'Here is some text, and here is the value:'.$items->value.'.';
foreach ( $somearray as $items ) {
echo $variable;
}
*note: I am using ezsql for database actions, hence the $items->value variable....
Make sense? I'm just trying to make my file easy to change for other situations... or is there a better way?
Thanks for looking and for your help.
Upvotes: 1
Views: 170
Reputation: 48887
or is there a better way?
Use a function/method:
function formatItems($items)
{
return 'Here is some text, and here is the value:'.$items->value.'.';
}
foreach ( $somearray as $items ) {
echo formatItems($items);
}
Using a function allows more complex formatting. If it's going to be as simple as your example, you could use printf, as suggested by lonesomeday.
If appropriate, you could have a display/format method in your Items class definition.
Upvotes: 1
Reputation: 238075
The nicest way to do this would, I think, be printf
. It's not exactly what you asked for, but I think it will make your code cleaner.
$variable = 'Here is some text, and here is the value:%s.';
foreach ($somearray as $items) {
printf($variable, $items->value);
}
The value passed as the second argument to printf
will be substituted into the code.
Upvotes: 1
Reputation: 5115
You can use eval()
, but you should be aware it's risky, and you better read about the consequences of using it.
Other than that, you can use it like you said, but escape the dollar sign so it won't get treated as a variable until the foreach, or use single quotes:
$variable = 'Here is some text, and here is the value: {$items->value}';
foreach ( $somearray as $items ) {
echo eval('return "'.$variable.'";');
}
Upvotes: 1
Reputation: 1377
$variable is set only once and takes on the value of $items->value at the time (which will probably result in an error since $items doesn't exist at that time and you are referencing a field.
what you want is this:
$variable = 'Here is some text, and here is the value: {$items->value}';
foreach ( $somearray as $items ) {
echo $variable;
}
Upvotes: -1
Reputation: 29508
Your $items
variable will be overwritten by your for loop - $variable
won't be though.
Upvotes: 0