-2

I'm using some functions to delete vars. My code is like:

<?
$arr['var1'] = 'Hello';
$arr['var2'] = 'world';
function foo(){
    global $arr;
    unset($arr['var2']);
} 
foo();

But in the PHP manual:

To unset() a global variable inside of a function, then use the $GLOBALS array to do so:

unset($GLOBALS['arr']['var2']);

Doesn't unset anything because $GLOBALS['arr']['var2'] doesn't exist. I only want to unset GLOBAL array element inside function.

It exists, because GLOBALS are supervariable and it has everything other var has.

edit:

I tried to do it but after I try to call foo() then i try to print_r($arr) it show both var1 and var2, and if I try print_r($GLOBALS['arr']['var2']) it show undefined index.... Maybe it's be config...

edit2

I mistyped it in my script. So it's working...

Full working code:

<?
$arr['var1'] = 'Hello';
$arr['var2'] = 'world';
function foo(){
    global $arr;
    unset($GLOBALS['arr']['var2']);
} 
foo();
Dan B.
  • 93
  • 1
  • 1
  • 12

2 Answers2

1

You can pass variable by reference:

$arr['var1'] = 'Hello';
$arr['var2'] = 'world';
function foo(&$a){
    unset($a['var2']);
}
foo($arr);

https://secure.php.net/manual/en/language.references.pass.php

Boshentz
  • 347
  • 2
  • 8
0

unset($GLOBALS['arr']['var2']); is correct.

see here https://3v4l.org/rCN5h

<?php
$arr['var1'] = 'Hello';
$arr['var2'] = 'world';
function foo(){
unset($GLOBALS['arr']['var2']);
}
var_dump($arr);
foo();
var_dump($arr);
hanshenrik
  • 19,904
  • 4
  • 43
  • 89