我从我的函数中得到一个未定义的索引错误

时间:2013-02-03 01:59:35

标签: php arrays function associative

function get_frequencies( $a )
{
  $get_frequencies = array();
  foreach( $a as $k => $v )
  { 
    $get_frequencies[$v]++ ;  //this is the line causing the error
  }
  return $get_frequencies;
}
/*Get Flip function involking and testing */        
$letter_freq = array("a" => "x", "c" => "y", "b" => "z", "d" => "y", "z" => "y");
$get_frequencies = get_frequencies( $letter_freq );
print_r($get_frequencies)

继承错误我得到的答案是正确的,但仍然会收到此错误。

Notice: Undefined index: x in
C:\Users\Marty2\Desktop\xampp\htdocs\lab13\array_library.php on line
235

Notice: Undefined index: y in
C:\Users\Marty2\Desktop\xampp\htdocs\lab13\array_library.php on line
235

Notice: Undefined index: z in
C:\Users\Marty2\Desktop\xampp\htdocs\lab13\array_library.php on line
235
Array ( [x] => 1 [y] => 3 [z] => 1 )

1 个答案:

答案 0 :(得分:2)

因为您正在尝试增加尚不存在的变量中的值。只需检查以确保它们存在,如果不存在,则实例化它们并为它们赋值零。然后你可以安全地增加它们的价值。

if (!isset($get_frequencies[$v]))
{
    $get_frequencies[$v] = 0;
}
$get_frequencies[$v]++;