dongzenglin8292 2012-12-24 10:17
浏览 147
已采纳

在foreach循环中使用PHP常量

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
} 
  • 写回答

2条回答 默认 最新

  • doudansui6650 2012-12-24 10:20
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃