How do you unset a variable variable representing an array element?
function remove($var) {
unset($$var);
}
$x=array('a'=>1,'b'=>2);
remove('$x["a"]');
var_dump(isset($x['a']));
The code above doesn't unset the array element x['a']. I need that same remove() function to work with $_GET['ijk'].
Just use unset() or the (unset) cast.
If you want to use a function to unset, something like this would be better.
function removeMemberByKey(&$array, $key) {
unset($array[$key]);
}
It works!
You can try,
function remove(&$var,$key) {
unset($var[$key]);
}
$x=array('a'=>1,'b'=>2);
remove($x,'a');
var_dump(isset($x['a']));
Variable variables cannot be used with superglobals, so if you need it to work for $_GET as well, you need to look at using a different method.
Source: http://php.net/manual/en/language.variables.variable.php
Try This:
<?php
/* Unset All Declair PHP variable*/
$PHP_Define_Vars = array_keys(get_defined_vars());
foreach($PHP_Define_Vars as $Blast) {
// or may be reset them to empty string# ${"$var"} = "";
unset(${"$Blast"});
}
?>
unset is easier to type then remove
When using it with an array element, the array will still exist
You could rewrite your function to treat the parameter as a reference;
EDIT: updated to use alex's code
function remove(&$array, $key){
unset($array[$key]);
}
remove($x,'a');
Related
Let's say I have some variables declared - but I don't know exactly which, I just have an array with variable names.
$variable_list = array('var1', 'var2', 'var3', 'var4');
We go ahead and assign some values.
foreach($variable_list as $var_name){
$$var_name = rand(100,1000);
}
Now I want to unset these variables in a similar fashion. Not remove them from list, but unset the ACTUAL variable.
foreach($variable_list as $var_name){
unset($var_name);
}
this does not work. any ideas?
foreach($variable_list as $var_name){
unset($$var_name);
}
PHP Manual
Why do you set them using variable variables ($$var_name) and don't unset them like that? This should work:
foreach($variable_list as $var_name){
unset($$var_name);
}
However, since you say:
Now I want to [...] not remove them from list, but unset the ACTUAL variable.
Simply use:
foreach($variable_list as $var_name){
$$var_name = null;
}
I got some trouble with in_array()
$list = array(
"files/" => "/system/application/files/_index.php",
"misc/chat/" => "/system/application/misc/chat/_index.php"
);
I have this $_GET['f'] which holds the string files/.
How can I search through the array for possible matches?
If the string is found in the array, then the file should be included
Thanks for any help :)
It's really simple. All you need to do is check if the array element is set. The language construct that's usually used is isset() (yes, it's that obvious)...
if (isset($list[$_GET['f']])) {
}
There's no need to call a function for this, isset is cleaner and easier to read (IMHO)...
Note that isset is not actually a function. It's a language construct. That has a few implications:
You can't use isset on the return from a function (isset(foo()) won't work). It will only work on a variable (or a composition of variables such as array accessing or object accessing).
It doesn't have the overhead of a function call, so it's always fast. The overall overhead of a function call is a micro-optimization to worry about, but it's worth mentioning if you're in a tight loop, it can add up.
You can't call isset as a variable function. This won't work:
$func = 'isset';
$func($var);
array_key_exists is a function that returns true of the supplied key is in the array.
if(array_key_exists( $_GET['f'], $list )) {
echo $list[$_GET['f']];
}
You can use in_array() in conjunction with array_keys():
if (in_array($_GET['f'], array_keys($list))) {
// it's in the array
}
array_keys() returns an array of the keys from its input array. Using $list as input, it would produce:
array("files/", "misc/chat/");
Then you use in_array() to search the output from array_keys().
Use array_key_exists.
if(array_key_exists($_GET['f'], $list)){
// Do something with $list[$_GET['f']];
}
in_array() searches array for key using loose comparison unless strict is set.
it's like below.
foreach ($array as $value){
if ($key == $value){
return true;
}
}
My way.
function include_in_array($key, $array)
{
foreach($array as $value){
if ( strpos($value, $key) !== false ){
return false;
}
}
}
I am familiar with scope but have not used it much. I know how to change a variable's value inside of a function if I know what the variable name is by using GLOBAL $variableName in the function.
I'm writing a method that is passed 2 arguments. The first will accept an array that contains strings and the second will hold settings to do such as md5 for encrypting and trim to trim spaces.
Is there a way I can change the first argument's value inside the function? or do you know of a better method to accomplish this?
function _Edit($string, $rules)
{
#check if array
if(is_array($rules)!=TRUE)
{array_push($GLOBALS[debug], '<span class="error">_Edits second arguement must be an array</span>');}
if(is_array($string)!=TRUE)
{array_push($GLOBALS[debug], '<span class="error">_Edits first arguement must be an array</span>');}else
{
#loop through the strings
foreach ($string as $sk=>$sv)
{
#make changes based on rules
/* order of rules is important.
the changes will be made in the order the rules are sent */
foreach ($rules as $rv)
{
switch ($rv)
{
case 'md5':
//$string[$sk] = md5($sv);
//GLOBALS[$string][$sk] = md5($sv);
break;
}
}
}
}
}
If I understand right, you want to change the value of the first argument outside of the function from inside the function? for this you will have to pass by reference, or you can just return the updated array and overwrite the original value.
http://php.net/manual/en/language.references.pass.php
Why don't you return the array you eventually modified in your function?
So...
$my_array = _Edit($my_array, $rules);
And in your function you do:
function _Edit($string, $rules) {
... your code ...
... modify $string ...
return $string;
}
Generally I pass an array of parameters to my functions.
function do_something($parameters) {}
To access those parameters I have to use: $parameters['param1']
What I would like to do, is run some sort of logic inside this function on those parameters that converts that array into normal variables. My main reasons is just that sometimes I have to pass a whole load of parameters and having to type $parameters['..'] is a pain.
foreach($parameters as $key=>$paremeter) {
"$key" = $parameter;
}
I thought that might work.. but no cigar!
Use extract():
function do_something($parameters) {
extract($parameters);
// Do stuff; for example, echo one of the parameters
if (isset($param1)) {
echo "param1 = $param1";
}
}
do_something(array('param1' => 'foo'));
Try $$key=$parameter.
Just extract the variables from array using extract:
Import variables into the current
symbol table from an array
extract($parameters);
Now you can access the variables directly eg $var which are keys present in the array.
There is the extract function. This is what you want.
$array = array('a'=>'dog', 'b'=>'cat');
extract($array);
echo $a; //'dog'
echo $b; //'cat'
I have a cookie which stores info in an array.
This is for a classifieds website, and whenever users delete their 'ads' the cookie must also be removed of the ad which was deleted.
So I have this:
if (isset($_COOKIE['watched_ads'])){
$expir = time()+1728000;
$ad_arr = unserialize($_COOKIE['watched_ads']);
foreach($ad_arr as $val){
if($val==$id){ // $id is something like "bmw_m3_10141912"
unset($val);
setcookie('watched_ads', serialize($ad_arr), $expir, '/');
}
}
}
This doesn't work... any idea why? I think its a problem with the unset part...
Also, keep in mind if there is only one value inside the array, what will happen then?
Thanks
You got two bugs here: 1) you unset the $val instead of the array element itself. 2) You set the cookie within the loop to the unknown $ad_arr2 array.
foreach($ad_arr as $key => $val){
if($val==$id){ // $id is something like "bmw_m3_10141912"
unset($ad_arr[$key]);
}
}
setcookie('watched_ads', serialize($ad_arr), $expir, '/');
array_filter seems appropriate:
$array = array_filter($array, create_function('$v', 'return $v != '.$id.';'));
You are correct that you are using unset incorrectly. The manual on unset states:
If a static variable is unset() inside
of a function, unset() destroys the
variable only in the context of the
rest of a function. Following calls
will restore the previous value of a
variable.
When you use 'as' you're assigning the value of that array element to a temporary variable. You want to reference the original array:
foreach ($ad_arr as $key => $val)
...
unset($ad_arr[$key]);
...