php数组报错Notice: Undefined index解决办法
很多时候使用php数组的时候,定义了数组,引用的时候,并没有定义的索引,会碰到一个注意级别的错误。
例如,
$arr = array ( "t" => "hello" ); print_r( $arr ); print ( $arr [ "t" ]); print ( $arr [ "a" ]); |
Array ( [t] => hello ) hello Notice: Undefined index: a in F:\test\index.php on line 5 |
解决办法是,每次做数组的使用的时候,用isset函数做个判断。
$arr = array ( "t" => "hello" ); print_r( $arr ); print (isset( $arr [ "t" ]) ? $arr [ "t" ] : "" ); print (isset( $arr [ "a" ]) ? $arr [ "a" ] : "" ); |
Array ( [t] => hello ) hello |
这样就解决了,注意级别的错误。
好用的使用数组的方式
为了解决每次使用数组都用isset函数判断,写了个函数。
$arr = array ( "t" => "hello" ); print_r( $arr ); print (getValue( $arr [ "t" ])); print (getValue( $arr [ "a" ])); function getValue( $str ) { return isset( $str ) ? $str : "" ; } |
Array ( [t] => hello ) hello Notice: Undefined index: a in F:\test\index.php on line 12 |
执行的时候还是有问题,分析一下,在getValue函数变量中,数组已经根据索引做了引用,所以也报了错误。最后决定,还是写个类把数组作为成员。
$arr = array ( "t" => "hello" ); print_r( $arr ); $tarr = new Arr( $arr ); print ( $tarr ->getValue( "t" )); print ( $tarr ->getValue( "a" )); if ( $tarr ->getValue( "t" )) { print ( "success" ); } else { print ( "error" ); } if ( $tarr ->getValue( "a" )) { print ( "success" ); } else { print ( "error" ); } class Arr { private $arr = array (); public function __construct( $arr ) { if ( is_array ( $arr )) { $this ->arr = $arr ; } } public function getValue( $key ) { return isset( $this ->arr[ $key ]) ? $this ->arr[ $key ] : "" ; } //一些自己写的操作数组的函数 } |
Array ( [t] => hello ) hello success error |
问题解决。
资料难找, 百度找不到谷歌找, 好不容在这里找了, 转过来,复制给大家用。
来源 http://dianjiaoren.com/article/201510/1.html
标签:没有标签呢
↑上一篇:零基础人员学习网络推广的方法及技巧
↓下一篇:贴吧扫盲!新人如何混好贴吧
