PHP - Ds\Stack::push() 函式



PHP 的Ds\Stack::push() 函式用於將指定的值壓入當前堆疊。由於堆疊遵循LIFO(後進先出)原則,所有元素始終被壓入頂部。

此函式允許您一次壓入多個值,透過單個操作新增多個值而不是一次一個值來節省時間。

語法

以下是 PHP Ds\Stack::push() 函式的語法:

public void Ds\Stack::push([ mixed $...values ])

引數

以下是此函式的引數:

  • values − 要壓入堆疊的一個或多個值。

返回值

此函式不返回值。

示例 1

以下是 PHP Ds\Stack::push() 函式的基本示例:

<?php 
   $stack = new \Ds\Stack([1, 2]);
   echo "The original stack elements: \n";
   print_r($stack);
   #using push() function
   $stack->push(3);
   $stack->push(4);
   $stack->push(5);
   echo "The map elements after push() function called: \n";
   print_r($stack);
?>

輸出

上述程式產生以下輸出:

The original stack elements:
Ds\Stack Object
(
    [0] => 2
    [1] => 1
)
The map elements after push() function called:
Ds\Stack Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)

示例 2

以下是 PHP Ds\Stack::push() 函式的另一個示例。我們使用此函式將指定元素“Tutorials”、“Point”和“India”逐個壓入堆疊:

<?php 
   $stack = new \Ds\Stack([]);
   echo "The original stack elements: \n";
   print_r($stack);
   #using push() function
   $stack->push("Tutorials");
   $stack->push("Point");
   $stack->push("India");
   echo "The map elements after push() function called: \n";
   print_r($stack);
?>

輸出

執行上述程式後,將顯示以下輸出:

The original stack elements:
Ds\Stack Object
(
)
The map elements after push() function called:
Ds\Stack Object
(
    [0] => India
    [1] => Point
    [2] => Tutorials
)

示例 3

一次將多個值壓入堆疊。

<?php 
   $stack = new \Ds\Stack([]);
   echo "The original stack elements: \n";
   print_r($stack);
   #using push() function
   $stack->push('a', 'e', 'i', 'o', 'u');
   echo "The map elements after push() function called: \n";
   print_r($stack);
?>

輸出

執行上述程式後,將生成以下輸出:

The original stack elements:
Ds\Stack Object
(
)
The map elements after push() function called:
Ds\Stack Object
(
    [0] => u
    [1] => o
    [2] => i
    [3] => e
    [4] => a
)
php_function_reference.htm
廣告