[PHP] data structure - sequential storage structure of linear table in PHP

Keywords: PHP

1. Arrays in PHP are actually ordered mappings, which can be regarded as arrays, lists, hash tables, dictionaries, collections, stacks, queues, not fixed lengths
2. If multiple cells in the array definition use the same key name, only the last one will be used, and the previous ones will be overwritten
3. If you want a parameter of a function to always be passed by reference, you can add a symbol before the parameter in the function definition&
4.PHP references are aliases, that is, two different variable names point to the same content; "by default, objects are passed by reference". But in fact, this is not entirely correct. When an object is passed as a parameter, returned as a result, or assigned to another variable, the other variable is not a reference to the original, but they all keep copies of the same identifier

<?php
class Sqlist{
        public $data=array();
        public $length=0;
}
//Insertion element
function listInsert(&$sqlist,$i,$e){
        //Is the position out of range
        if($i<1 && $i>$sqlist->length+1){
                return false;
        }   
        //Starting from the insertion position, all subsequent elements are retired
        if($i<=$sqlist->length){//The position to insert is not at the end
                for($k=$sqlist->length-1;$k>=$i-1;$k--){
                        $sqlist->data[$k+1]=$sqlist->data[$k];
                }   
        }   
        //New element insertion
        $sqlist->data[$i-1]=$e;
        //Length plus 1
        $sqlist->length++;
        return true;
}
//Get elements
function getElement($sqlist,$i,&$e){
        if($sqlist->length==0 || $i<1 || $i>$sqlist->length){
                return false;
        }   
        $e=$sqlist->data[$i-1];
        return true;
}
//Delete elements
function listDelete($sqlist,$i,&$e){
        if($sqlist->length==0 || $i<1 || $i>$sqlist->length){
                return false;
        }   
        $e=$sqlist->data[$i-1];
        //If it's the last element
        if($i!=$sqlist->length){
                //Move the element one bit forward after deleting the position
                for($k=$i-1;$k<=$sqlist->length-1;$k++){
                        $sqlist->data[$k]=$sqlist->data[$k+1];
                }   
        }   
    
        $sqlist->length--;
}

//Insert linear table
$sqlist=new Sqlist();
listInsert($sqlist,1,"Tau");
listInsert($sqlist,1,"Shihan");
//Get elements
$e="";
getElement($sqlist,2,$e);
echo $e."\n";//Output Tau

//Delete elements
listDelete($sqlist,1,$e);


var_dump($sqlist);

Posted by kaveman50 on Fri, 03 Jan 2020 15:21:41 -0800