如果数组的最后一个元素为空,如何删除它


How to delete the last element of an array if it is empty

下面是我的数组($hamle)的print_r版本。正如您所看到的,索引(80)是空的,或者有一个行尾或类似的字符。如果它存在并且是空的,我尝试了很多选项来删除它,但都做不到。我强烈认为它是在"read-while"循环中读取空行。它不会出现在所有文件中。它有时会出现。有人能想出一条时髦的出路吗?

Array ( [0] => 1.b4 [1] => d5 [2] => 2.Bb2 [3] => Qd6 [4] => 3.a3 [5] => e5 [6] => 4.e3 [7] => a5 [8] => 5.b5 [9] => Nf6 [10] => 6.c4 [11] => Bg4 [12] => 7.Be2 [13] => Bxe2 [14] => 8.Qxe2 [15] => Nbd7 [16] => 9.d4 [17] => dxc4 [18] => 10.Nf3 [19] => e4 [20] => 11.Ne5 [21] => Nb6 [22] => 12.Nd2 [23] => Qe6 [24] => 13.O-O [25] => Bd6 [26] => 14.Nexc4 [27] => Nxc4 [28] => 15.Nxc4 [29] => O-O [30] => 16.Rfc1 [31] => Be7 [32] => 17.a4 [33] => Nd5 [34] => 18.Ba3 [35] => Bb4 [36] => 19.Qb2 [37] => Rfc8 [38] => 20.Bxb4 [39] => axb4 [40] => 21.Nd2 [41] => c6 [42] => 22.b6 [43] => Qe7 [44] => 23.Rc5 [45] => Ra6 [46] => 24.a5 [47] => g6 [48] => 25.Nb3 [49] => Rca8 [50] => 26.Rac1 [51] => Kg7 [52] => 27.Qd2 [53] => Qd6 [54] => 28.R1c4 [55] => Rd8 [56] => 29.Rxb4 [57] => Nxb4 [58] => 30.Qxb4 [59] => Qe7 [60] => 31.h3 [61] => Rd5 [62] => 32.Kf1 [63] => Ra8 [64] => 33.Qa4 [65] => Qd6 [66] => 34.Ke2 [67] => Kf8 [68] => 35.Rxd5 [69] => cxd5 [70] => 36.Nc5 [71] => Ke7 [72] => 37.Qb5 [73] => Rb8 [74] => 38.Kd2 [75] => f5 [76] => 39.Kc3 [77] => g5 [78] => 40.Kb4 [79] => 1-0 [80] => )

代码=>

while(! feof($file))
  {

 $n=$n+1;
            $hamle1= fgets($file);
    $hamle1 = str_replace("'n", "", $hamle1);
    $hamle1 = str_replace("'r", "", $hamle1);
    $hamle1 = trim($hamle1);
    $hamle1 = explode(" ", $hamle1);
        foreach($hamle1 as $item)
    {
        $hamle[] = $item;
    }

array_filter将删除空条目

$hamle = array_filter($hamle);

若要删除数组的最后一个元素(如果它为空),请使用以下代码。

// get the last element of array
if(trim(end($hamle)) == '')
{
   // Remove last element from array
   array_pop($hamle) ;
}

请访问以下链接以了解上述代码中使用的功能。

微调

结束

array_pop