略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: ArrayObject::offsetUnset

2024-11-15

ArrayObject::offsetUnset

(PHP 5, PHP 7, PHP 8)

ArrayObject::offsetUnsetUnsets the value at the specified index

说明

public ArrayObject::offsetUnset(mixed $key): void

Unsets the value at the specified index.

参数

key

The index being unset.

返回值

没有返回值。

范例

示例 #1 ArrayObject::offsetUnset() example

<?php
$arrayobj 
= new ArrayObject(array(0=>'zero',2=>'two'));
$arrayobj->offsetUnset(2);
var_dump($arrayobj);
?>

以上例程会输出:

object(ArrayObject)#1 (1) {
  [0]=>
  string(4) "zero"
}
add a noteadd a note

User Contributed Notes 2 notes

up
3
pvenakis at efront dot gr
14 years ago
When traversing recursively nested arrays using an RecursiveIteratorIterator, you cannot offsetUnset() or offsetSet() sub-array values, unless they are *all* declared as ArrayObject.
up
1
oalexandrino at yahoo dot com dot br
15 years ago
Be careful when you are working with collections. This method works with the reference of an array instead of its retrieved value.

So, you can do a mistake.

In order to understand have a look at code as follow:

<?php
class Employee
{
    public function
__construct()
    {
    }   
}

class
Company
{
    private
$arrEmployee;
   
    public function
__construct()
    {
    }   
   
    public function
AddEmployee(Employee $oEmployee)
    {
       
$this->arrEmployee[] = $oEmployee;   
   
    }
   
    public function
getEmployeeList()
    {
        return
$this->arrEmployee;
           
    }
   
}
?>

<?php

// first, creates the Company object
$oCompany = new Company();

// second, add 10 elements in
foreach( range(0, 9) as $index )
{
   
$oCompany->AddEmployee( new Employee() );
}

// get them
$arrEmployee = $oCompany->getEmployeeList();

// creates an ArrayObject from "$arrEmployee"
$arrayobject = new ArrayObject($arrEmployee);

// unsets its firt five elements
foreach( range(0, 4) as $index )
{
   
$arrayobject->offsetUnset($index);
}

// get them again
$arrEmployee = $oCompany->getEmployeeList();

// it shows just 5 elements, they were removed as reference via "offsetUnset" method
print_r($arrEmployee) ;

?>

官方地址:https://www.php.net/manual/en/arrayobject.offsetunset.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3