Reputation: 453
Is there any way to call/compose a constant name in PHP, which does not require the use of eval?
I mean, I have several constant names following this schema:
define("CONSTANT_0", "foo 0");
define("CONSTANT_1", "foo 1");
define("CONSTANT_2", "foo 2");
and I want to be able to go through those values in a loop, something like this:
for ($i=0; $i<3; $i++)
echo CONSTANT_$i;
I can't use variables here because I'm using a pre-defined shared class, which already contains those values.
Thanks in advance
Upvotes: 0
Views: 96
Reputation: 34416
If you want a really robust way to search your constants or only return specific constants you can use defined()
, get_defined_constants()
and constant()
:
define("CONSTANT_0", "foo 0");
define("CONSTANT_1", "foo 1");
define("CONSTANT_2", "foo 2");
define("NOT_1", "bar 1");
$all_constants = get_defined_constants(true);
$search = 'CONSTANT_';
for ($i = 0; $i < count($all_constants['user']); $i++) {
if(defined($search . $i)){
echo constant($search . $i);
}
}
The constants you define will always be in the 'user' array returned from get_defined_constants()
(there are at least 3 sub-arrays returned when you call this function). You can count the 'user' array and then determine if your search term is defined. As you see in the example above, only those constants defined with the search term CONSTANT_
are echoed during the loop.
If you want another method consider the following function:
function returnMyConstants ($prefix) {
$defined_constants = get_defined_constants(true);
foreach ($defined_constants['user'] as $key => $value) {
if (substr($key, 0, strlen($prefix)) == $prefix) {
$new_array[$key] = $value;
}
}
if(empty($new_array)) {
return "Error: No Constants found with prefix '$prefix'";
} else {
return $new_array;
}
}
print_r(returnMyConstants('CONSTANT_'));
The output of this function is:
Array
(
[CONSTANT_0] => foo 0
[CONSTANT_1] => foo 1
[CONSTANT_2] => foo 2
)
This function will allow you to search the 'user' portion of the defined constants and then uses well known array parsing methods for the rest. The function can be easily modified, but returns an array of your constants with the proper prefix. It is much more portable, requiring no hard coding of the search value.
Upvotes: 0
Reputation: 1
I can iterate trough your constants with the function get_defined_constants which return an associative array with all user-defined constants and PHP constants (constant name associated with its value)
To iterate through your (user-defined) constants : $c = get_defined_constants(true)["user"];
Upvotes: 0
Reputation: 31749
This would help -
define("CONSTANT_0", "foo 0");
define("CONSTANT_1", "foo 1");
define("CONSTANT_2", "foo 2");
for ($i=0; $i<3; $i++) {
echo constant('CONSTANT_' . $i);
}
Output
foo 0foo 1foo 2
Upvotes: 2