How Can I Implement Stack in PHP?

A Stack is a linear data structure that follows a particular order in which the operations are performed. This order is called LIFO(Last In, First Out). The element inserted last is the first element to be popped.

In Stack, insertion and deletion operations are called push and pop.

We can implement it in both a procedural or object-oriented approach. Here I follow the procedural process.

$data_array = [];
$top = -1;

function push($top, $item, $data_array){
    global $top,$data_array;
    $data_array[$top] = $item;
    return $data_array;

function pop(){
    global $top,$data_array;
    if($top < 0)
        return -1;
    $top_item = $data_array[$top];
    return $top_item;
push($top, 1, $data_array);
push($top, 2, $data_array);
push($top, 3, $data_array)


Leave a Reply

Your email address will not be published. Required fields are marked *