array_pop

array_pop(array &$array): mixed

弹出(删除并返回)数组末尾的最后一个元素,数组长度减一。

C C23

C23
#include <stdio.h>

int main(void) {
    const char *stack[] = {"a", "b", "c"};
    int size = 3;
    const char *last = stack[--size];
    printf("%s\n", last);
    printf("size=%d\n", size);
    return 0;
}
输出
c
size=2

C++ C++26

C++26
#include <iostream>
#include <vector>
int main() {
    std::vector<std::string> stack{"a", "b", "c"};
    std::string last = stack.back();
    stack.pop_back();
    std::cout << last << "\n";
    std::cout << stack.size() << "\n";
    return 0;
}
输出
c
2

C# v11.0.100

v11.0.100
var stack = new List<string> { "a", "b", "c" };
string last = stack[^1];
stack.RemoveAt(stack.Count - 1);
Console.WriteLine(last);
Console.WriteLine(stack.Count);
输出
c
2

Go v1.27.4

v1.27.4
package main

import "fmt"

func main() {
    stack := []string{"a", "b", "c"}
    last := stack[len(stack)-1]
    stack = stack[:len(stack)-1]
    fmt.Println(last)
    fmt.Println(len(stack))
}
输出
c
2

Java v27.0.1

v27.0.1
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> stack = new ArrayList<>(List.of("a", "b", "c"));
        String last = stack.remove(stack.size() - 1);
        System.out.println(last);
        System.out.println(stack.size());
    }
}
输出
c
2

JavaScript v26.13.1

v26.13.1
const stack = ["a", "b", "c"];
const last = stack.pop();
console.log(last, stack);
输出
c [ 'a', 'b' ]

PHP v8.6.0

v8.6.0
$stack = ["a", "b", "c"];
$last = array_pop($stack);
echo $last, "\n", json_encode($stack);
输出
c
["a","b"]

Python v3.15.2

v3.15.2
stack = ["a", "b", "c"]
last = stack.pop()
print(last, stack)
输出
c ['a', 'b']

Rust v1.99.1

v1.99.1
fn main() {
    let mut stack = vec!["a", "b", "c"];
    let last = stack.pop().unwrap();
    println!("{} {:?}", last, stack);
}
输出
c ["a", "b"]

TypeScript v26.13.1

v26.13.1
const stack: string[] = ["a", "b", "c"];
const last: string | undefined = stack.pop();
console.log(last, stack);
输出
c [ 'a', 'b' ]

语言差异说明

C:没有内置弹栈,惯用 --size 递减计数即可,无需真的删数据。

C++:没有内置弹栈,分两步 back() 取值 + pop_back() 删除(pop_back 不返回值)。

C#:没有专门 pop,惯用 [^1] 取尾 + RemoveAt(Count-1),或改用 Stack<T>。

Go:没有内置弹栈,用切片 reslice s[:len(s)-1](底层数组不收缩,末尾元素仍被引用时阻碍回收)。

JavaScript:pop() 返回 undefined。

PHP:各语言弹栈语义一致——取末尾元素并让长度减一;差异集中在空数组行为:array_pop([]) 返回 null 并发出 warning。

Python:pop() 抛 IndexError。

Rust:Vec::pop 用 Option<T> 表达(空数组得到 None,类型系统强制处理)。

TypeScript:同 JavaScript,pop() 返回 undefined。