简体   繁体   中英

Using of PHP constants in foreach loop

I need to use PHP contants in foreach loop:

define('WEBS', 'http://google.com, http://yahoo.com');
foreach (WEBS as $a) {
    //do something
}

However I managed to do that by following code, although it works fine but aptana editor shows syntax error. Please guide me how to do that in the correct manner.

foreach (get_defined_constants(true)['user']['WEBS'] as $w) {
//do something
} 

You have to explode the values first

foreach (explode(', ', WEBS) as $url) { ...

explode() will break a string into an array so that you can iterate through it


Alternatively, you could even use preg_split .

foreach(preg_split('/,\s*/', WEBS) as $url) { ...

preg_split() allows you to split your string based on a regular expression. It returns an array. As an example, using this regex, the space following the comma is optional.

# a string like this
foo.com, hello.com,world.com,  test.com

# would still split properly to
[
  'foo.com',
  'hello.com',
  'world.com',
  'test.com'
]

Regex methods are not always necessary. But I thought I'd show you that a little more control is available when it's necessary.


Aptana is showing you an error because you can't use [] after a func() prior to PHP 5.4. To get around that, you can do things like:

$constants = get_defined_constants(true);
$constants['user']['WEBS'];

But in this case WEBS should be just fine. The only issue you were having is that you needed to convert the string to an array first.

Looks like misuse of constants.

It seems you need a regular variable of array type.

$webs = array('http://google.com', 'http://yahoo.com');
foreach ($webs as $a) {
    //do something
}

If you still thinks that constants is what you need - better ask another question, explaining why so, and be told of what you're doing wrong

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM