将变量传递给数组索引

时间:2013-02-12 00:05:22

标签: php arrays debugging multidimensional-array indexing

这就是我所拥有的

foreach ( $post_formats as $format ) {
    if ( $options['show_post_formats'][$format] == 0 ) {
        $format = 'post-format-' . $format;
        array_push( $hide, $format );
    }
}

并且它工作正常...但是给我一个未定义的索引:我调试时出错,因为它希望$ format的值在引号中。我该怎么做呢?

1 个答案:

答案 0 :(得分:3)

因为您不确定索引是否存在,您只需使用!empty()并检查数组键是否存在。

<?php 
foreach ( $post_formats as $format ) {
    if (!empty($format) && array_key_exists($format, $options['show_post_formats']) && $options['show_post_formats'][$format] == 0 ) {
        $format = 'post-format-' . $format;
        array_push( $hide, $format );
    }
}
?>