Monday, September 7, 2015

array stack class to demonstrate push pop first last

<?php
class Stack {
    private $array = array(2, 3, 4, 5);
    public function print_array(){
        print_r( $this->array );
    }
    public function push_to_array($value){
        $this->array[] = $value;
    }
    public function pop_from_array(){
        $count = count($this->array) - 1;
        if(empty($this->array[$count])){
           echo 'array is empty';
        } else{
            $pop_value = $this->array[$count];
            unset($this->array[$count]);
            return $pop_value;
        }
    }
    public function last(){
        if(empty($this->array[0])){
            return 'array is empty';
        } else{
            return $this->array[0];
        }
    }
    public function first(){
        $count = count($this->array) - 1;
        if(empty($this->array[$count])){
            return 'array is empty';
        } else{
            return $this->array[$count];
        }
    }

}

$array = new Stack();
echo $array->pop_from_array();
$array->print_array();

No comments:

Post a Comment

css snippet for blogger code highlighting

code, .code {     display: block;     background: beige;     padding: 10px;     margin: 8px 15px; }