I have an array that I would like to clear the values out of and I'm wondering what the best way to accomplish this is.
I tried setting it to nothing:
$array = array();
... later on
$array = "";
Afterwards I'll add new values to it later:
foreach($something as $thing):
$array[] = $thing['item'];
endforeach;
And it seems to have done what I needed it too. But after a quick search online I'm seeing a lot of recommendations to do the following instead:
unset($array);
$array = array();
Is there any difference between this action and the one I performed up top?
Setting $array to "" sets your variable to a string value, and unset removes the variable. Since you are just trying to clear the array, then $array = array() should be good enough.
I believe that array() explicitly defines it as an array. Your first statement $array = "" sets it to an empty string. Using unset will "reset" the variable, so it's neither a string or array until you assign a value to it, and $array = array() simply defines it as a new blank array.
Related
Which is the best (performance efficiency) way to create an array in multiple files?
This:
$arr = array();
$arr["key1"] = "val1";
$arr["key2"] = "val2";
include "arr_2.php";
arr_2.php:
$arr["key3"] = "val3";
$arr["key4"] = "val4";
Or this:
$arr = array("key1"=>"val1", "key2"=>"val2");
include "arr_2.php";
arr_2.php:
$arr = array_merge($arr, array("key3"=>"val3", "key4"=>"val4"));
ARRAY KEY => VALUE is faster than ARRAY_MERGE.
KEY VALUE is a simple creation of ARRAY ELEMENTS similar to creating a simple variable and assigning a value to it.
ARRAY_MERGE will always take previous array and merge values all over again, which involves more processing.
You will notice significant performance impact when run in a loop.
Hope this helps!
I have an array containing several keys, values, objects etc.. I need to empty that array but I'd like to do it in the most efficient manner.
The best I can come up with is:
foreach ($array as $key => $val) unset($array[$key]);
But I don't like the idea of having to loop through the array to just empty it.. surely there's a nice slick/clever way of doing this without wasting memory creating a new array?
Note: I'm not sure myself if it does cost extra memory in creating the array as new again. If it doesn't then $array = new array(); would be a fine way of 'emptying' it.
Just try with:
$array = array();
It highly depends on what you mean.
To empty the current reference you can always do
$array = array();
To completely remove the current instance from the scope
unset($array);
Unfortunately both of these cases don't necessarily mean the memory associated with each element is released.
PHP works with something called "references" for your variables. Your variables are actually labels or references pointing to data, not the actual container for data.
The PHP garbage collector can offer more insight on this subject.
Now take a look at this example, taken from the docs:
$a = "new string";
$c = $b = $a;
xdebug_debug_zval( 'a' );# a: (refcount=3, is_ref=0)='new string'
unset( $b, $c );
xdebug_debug_zval( 'a' );# a: (refcount=1, is_ref=0)='new string'
This unfortunately applies to all your variables. Including arrays. Cleaning up the memory associated with the array is a whole different subject I'm afraid.
I've noticed a longer discussion in the comments regarding using unset() on each individual key.
This feels like extremely bad practice. Consider the following code:
class A{
function __construct($name){$this->name=$name;}
function __destruct(){echo $this->name;}
}
$a=array();
$b=array();
$c=array();
for($i=0;$i<5;$i++) {
$a[]=new A('a');
$b[]=new A('b');
$c[]=new A('c');
}
unset($a);
$b=array();
echo PHP_EOL.'done'.PHP_EOL;
This will output:
aaaaabbbbb
done
ccccc
When the reference to a particular data structure reaches 0, it is cleaned from memory.
Both =array() and unset will do the same thing.
Now if you don't actually need array() you can use null :
$array=null;
This keeps the label in memory, but removes the reference it held to any particular data.
It's simple:
$array = array();
$array will be existing and type of array (but empty), and your data can be garbaged later from memory.
Well... why not: $array = array(); ?
As Suresh Kamrushi pointed out, I could use array_keys:
foreach (array_keys($array) as $key) unset($array[$key]);
This is probably the nicest solution for now.. but I'm sure someone will come up with something better soon :)
Try this:
// $array is your original array
$array = array_combine( array_keys( $array ), array_fill( 0, count($array), 0 ) );
The above will blank your array keeping the keys intact.
Hope this helps.
I have a bunch of arrays, which are stored in different variables like $required, $reserved, etc...
I would like to allow (inside a function) an array of options to be passed (like $options = array('required', 'reserved')), and that array would then be used to define which arrays to merge together and return at the end of the function.
So, I have this code in part of the function, that should grab all the options and merge the arrays, using variable variables to get the arrays from the strings passed in the options array):
$array = array();
foreach ($options as $key) {
$array_to_merge = ${$key};
array_merge($array, $array_to_merge);
}
return $array;
However, when I return the $array, it shows 0 items. If I print_r($array_to_merge);, I actually get the entire array as I should.
Does array_merge() simply not work with variable variables, or am I missing something here...?
array_merge returns the merged array, you're not assigning that return value to anything and thus it is being lost.
$array = array_merge($array, $array_to_merge);
should fix your problem.
If I read it right you can also simplify your code (replaces the loop) to just:
$array = call_user_func_array("array_merge", compact($options));
compact replaces the variable variable lookup and gets the list of arrays. And in effect there is only one array_merge call necessary.
I want to add an element to the beginning of an array, but this array might be empty sometimes. I've tried using array_unshift() but it doesn't seem to like empty arrays... should I simply check for the empty array and append the element manually, or does array_unshift() not mind empty arrays but I'm just being a klutz?
Here is my code at the moment:
$sids = array();
$sids = explode(",", $sid['sids']);
array_unshift($sids, session_id());
The contents of the $sids array are taken from a database and are comma separated values.
Thanks,
James
EDIT
I've managed to fix this now - sorry everyone!
Here's the updated code:
$sids = array();
if(!empty($row['sids']))
{
$sids = explode(",", $row['sids']);
}
array_unshift($sids, session_id());
If $sid['sids'] is empty, explode will return FALSE
Then $sids will be equal to FALSE
and the subsequent call to array_unshift will fail.
You should probably make sure $sids is an array before calling array_unshift.
Here's a way to do it:
if(!empty($sid['sids']))
$sids = explode(",", $sid['sids']);
else
$sids = array();
array_unshift($sids, session_id());
First off, your first line of code is pointless; explode always returns a value, whether it be an array or FALSE. You're guaranteed to overwrite that value once you call explode.
Secondly, your code should work. One minor edit I'd make is this:
<?php
$sids = array();
$sids = explode(",", $sid['sids']);
if(is_array($sids))
array_unshift($sids, session_id());
?>
Because (even though your code says otherwise, and that the PHP documentation says otherwise), explode may not always return an array.
Another piece of information that may be useful is whether or not there was any error being reported, and, if so, what the error was.
Best of luck!
array_unshift() accepts the array parameter by reference. This means it must actually be a variable, not an expression like array(). It also means it will modify the variable you pass, not return a new array with the element added. Here's an example to illustrate this:
$array = array();
array_unshift($array, 42);
var_dump($array); // Array now has one element, 42
$sids = explode(",", $sid['sids']);
if (!is_array($sids)) {
$sids = array();
}
array_unshift($sids, session_id());
i want to be able to change the last key from array
i try with this function i made:
function getlastimage($newkey){
$arr = $_SESSION['files'];
$oldkey = array_pop(array_keys($arr));
$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);
$_SESSION['files'] = $arr;
$results = end($arr);
print_r($arr);
}
if i call the function getlastimage('newkey') it change the key!but after if i print the $_SESSION the key is not changed? why this?
When you set $arr = $_SESSION['files'], you are actually making a copy of $_SESSION['files']. Everything you do to $arr is not done to the original.
Try this:
$arr =& $_SESSION['files'];
Note the ampersand after the equals sign. That will make $arr a reference to $_SESSION['files'], and your updates to $arr will affect $_SESSION['files'] as well, since they both reference the same content.
The other solution is of course to just copy the array back by putting $_SESSION['files'] = $arr; at the end of your function.
Wow, your code is a mess!
1) You're setting $_SESSION in a new array. In order for your changes to take affect, you'll need to set back to your original $_SESSION array, otherwise your new array will just be forgotten.
2) It would be easier to simply array_pop() to get the last element and set it to the new key, rather than wasting the time to fetch all the keys and pop the last key off, then fetch the value from the array again. The old key value is worthless.
try update the session
$_SESSION['files'] = $arr;