php array_push() -> How not to push if the array already contains the value

前端 未结 9 1937
无人共我
无人共我 2020-12-29 01:04

I am using the following loop to add items to an an array of mine called $liste. I would like to know if it is possible somehow not to add $value to the $liste array if the

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-29 01:38

    I have another solution for you! You can use keys as values And keys will never be duplicated.

    $arr = ["A" => true, "B" => true, "C" => true];
    
    $item = "A";
    $arr[$item] = true;
    

    Usage:

    foreach($arr as $value => $helper){
        echo $value;
    }
    

    Set class

    OK, Let me write a class for you! The arrays do not allow duplicated items are called sets.

    class Set{
        private $countainer;
    
        public function get(){
            return $this->container;
        }
        public function push($item){
            $this->container[$item] = true;
        }
        public function delete($item){
            unset($this->container[$item]);
        }
    }
    

    Note: This will not work for associative arrays and values.

提交回复
热议问题