php數組指標學習筆記(一)

來源:互聯網
上載者:User
有這麼一個問題,一個數組隊列,數組長度是固定的,當向輸入插入元素時,超過最大長度後,數組自動頭開始再覆蓋填充。

這時候,整個數組就形成了一個環形。如。


// 定義一個數組

$test_array = array();
function push_array($value, &$test_array) {
if (count($test_array) < 12) {

// 當數組小於指定長度時,直接添加元素

$test_array[] = $value;
} else {

// 當數組大於指定長度時,使用each取出當前指標的元素,並指標下移

list($k, $v) = each($test_array);

// 一般使用模數演算法,取得待覆蓋的key,然後直接覆蓋就可以了

$k = $k % 12;
$test_array[$k] = $value;
}
}
push_array(0,$test_array);
push_array(1,$test_array);
push_array(2,$test_array);
push_array(3,$test_array);
push_array(4,$test_array);
push_array(5,$test_array);
push_array(6,$test_array);
push_array(7,$test_array);
push_array(8,$test_array);
push_array(9,$test_array);
push_array(10,$test_array);
push_array(11,$test_array);
push_array(12,$test_array);
push_array(13,$test_array);
push_array(14,$test_array);
push_array(15,$test_array);
push_array(16,$test_array);
push_array(17,$test_array);
push_array(18,$test_array);
push_array(19,$test_array);
push_array(20,$test_array);
push_array(21,$test_array);
push_array(22,$test_array);
push_array(23,$test_array);
push_array(24,$test_array);
var_dump($test_array);exit;

測試結果:

array(12) {  [0]=>  int(24)  [1]=>  int(13)  [2]=>  int(14)  [3]=>  int(15)  [4]=>  int(16)  [5]=>  int(17)  [6]=>  int(18)  [7]=>  int(19)  [8]=>  int(20)  [9]=>  int(21)  [10]=>  int(22)  [11]=>  int(23)}

除了each以外,下面的數組指標函數也很好用

  • current() - 返回數組中的當前元素的值
  • end() - 將內部指標指向數組中的最後一個元素,並輸出
  • next() - 將內部指標指向數組中的下一個元素,並輸出
  • prev() - 將內部指標指向數組中的上一個元素,並輸出
  • reset() - 將內部指標指向數組中的第一個元素,並輸出

以上就介紹了 php數組指標學習筆記(一),包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.