How Can I Implement Stack in PHP?

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

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

We can implement it in both procedural or object oriented approach. Here i follow the procedural approach.

$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 *