$array["key"] = value; or array_merge(), which is the fastest way? - php

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!

Related

PHP Unify duplicate array

in my PHP code I have many array like this:
0 = ['attr_id':1,'name':'qty','value':'100'];
1 = ['attr_id':1,'name':'qty','value':'200'];
2 = ['attr_id':1,'name':'qty','value':'500'];
3 = ['attr_id':2,'name':'price','value':'10$'];
I want merge this array like this:
0 = ['attr_id':1,'name':'qty','value':['100','200','500']];
1 = ['attr_id':1,'name':'price','value':'10$'];
can you guys help me please?
thanks
This should be simpler. Build the result using the attr_id as the index and append the value:
foreach($array as $values) {
$result[$values['attr_id']]['value'][] = $values['value'];
$result[$values['attr_id']] = $result[$values['attr_id']] + $values;
}
If you need to reindex, just use array_values() on the $result.
This is one method where you loop through an array_column array of the id's and use key to insert values from values array.
$value = array_column($arr, 'value');
$id = array_column($arr, 'attr_id');
$res =[];
Foreach($id as $key => $i){
If(!isset($res[$i])) $res[$i] = ['attr_id' => $i, 'name'=>'qty', 'value' => []];
$res[$i]['value'][] = $value[$key];
}
Var_dump($res);
https://3v4l.org/VXI5E
As you see I use the id as key to keep track of the result array.
If you want to clear this, meaning reset the counting from 0, use array_values.
$res = array_values($res);
Edit: also the 10$ is inside an array in my answer, this makes it easier to use the array later in my opinion.
If you must save it as an string I can fix it, but it will probably be harder to use the array later with a mixed item.

set the variables that go inside array_merge_recursive

I need to tell array_merge_recursive what variables it needs to merge
I have the variable names that I need to use as strings, for example I have the following
$array1 = array('color'=>'blue', 'taste'=> 'sour', 'size'=>'big');
$array2 = array('color'=>'green', 'taste'=> 'sweet', 'size'=>'medium');
$array3 = array('color'=>'black', 'taste'=> 'sour', 'size'=>'small');
$array4 = array('color'=>'grey', 'taste'=> 'sweet', 'size'=>'big');
$allarrays = array_merge_recursive($array1, $array2, $array3, $array4);
This will work okay and merge my arrays, but I need to add a foreach to get the list of the arrays that I need and to set the array's that are going to the merged.
$arraysThatINeedToAddToTheMerge = array('array2', 'array4');
foreach ($arraysThatINeedToAddToTheMerge as $data){
$toBeMerged[] = $data;
}
$allarrays = array_merge_recursive($toBeMerged);
This doesn't work as it looks like I cannot use an array as the arguments for the array_merge_recursive.
I was thinking maybe I can use the list function for this but I haven't used it yet, what can I use to get what I need?
Two elements to handling this the way you want to:
Variable variables to build the to be merged array
$arraysThatINeedToAddToTheMerge = array('array2', 'array4');
$toBeMerged = [];
foreach ($arraysThatINeedToAddToTheMerge as $data){
$toBeMerged[] = $$data;
}
This will build an array of arrays, rather than simply an array of the names of your variables;
And (a modern PHP solution) then unpack the array arguments to be merged when calling array_merge_recursive
$allarrays = array_merge_recursive(...$toBeMerged);
or use call_user_func_array() for older versions of PHP
$allarrays = call_user_func_array('array_merge_recursive', $toBeMerged);

Best practice for clearing an array

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.

Most efficient way to empty an array

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.

PHP: Recursively set array values to equal keys (Codeigniter)

I am taking over a large project, and a lot of nested arrays are defined for option select lists to be used with form_dropdown() and form_multiselect() in Codeigniter. However, these arrays simply have values set and not corresponding keys.
Here's an example:
$lists['roomItems'] = array('Private telephone','Television cable/satellite','Personal furniture/decorations','Computer','Radio');
$lists['busRoute'] = array('Yes','No');
$lists['transport'] = array('Medical appointments','Dental appointments','Dialysis center','Wound care center','Religious services',
'Shopping services');
What I'd like to do is recursively go through $lists and make the keys equivalent to the values. For a single array, I tried foreach($lists['roomItems'] as $key=>value) and tried setting the key equal to the value, but it didn't take.
Can anyone help? I have about 30 items in the $lists array plus other ones that I'd re-use this code, so simply manually changing the pointers isn't really something I'd like to do. Thanks!
mhmmm what about:
$newList = array();
foreach($lists as $k=>$v) $newList[$k] = array_combine($v,$v);
should do the trick

Categories