Reputation: 3289
What is the difference in the following array notations: $arr[$key] = $value and $arr[] = $value, which is a better way ?
function test(){
$key = 0;
$a = array(1,2,3,4,5);
foreach($a as $value){
$a[$key] = $value;
$key++;
}
print_r($a);
}
versus
function test(){
$a = array(1,2,3,4,5);
foreach($a as $value){
$a[] = $value;
}
print_r($a);
}
Upvotes: 0
Views: 546
Reputation: 1806
If you want to append an element to the array I would use
$arr[] = $value;
It is simpler and you get all the information on that line and don't have to know what $key is.
Upvotes: 0
Reputation: 5349
One ($a[$key] = $value
) youare specifying the $key
where PHP will override that array entry if you use the same key twice.
The other ($a[] = $value
) PHP is handling the keys itself and just adding the array entry using the next available key.
The whole thing that you are doing is a bit redundant though, as in the first example you are trying to loop through the array setting its values to itself. In the second example you are duplicating the array.
Upvotes: 0
Reputation: 943615
$arr[$key] = $value
sets a specific key to a specific value.
$arr[] = $value
adds a value on to the end of the array.
Neither is "better". They serve completely different roles. This is like comparing writing and drawing. You use a pen for both of them, but which you use depends on the circumstance.
Upvotes: 0
Reputation: 165201
They are different.
$a[] = 'foo';
Adds an element to the end of the array, creating a new key for it (and increasing the overall size of the array). This is the same as array_push($array, 'foo');
$key = 0;
$a[$key] = 'foo';
Sets the 0
element of the array to foo
, it overwrites the value in that location... The overall size of the array stays the same... This is the same as $array = array_slice($array, 0, 1, 'foo');
(but don't use that syntax)...
In your specific case, they are doing 2 different things. The first test
function will result in an array array(1,2,3,4,5)
, whereas the second one will result in array(1,2,3,4,5,1,2,3,4,5)
. []
always adds new elemements to the end.... [$key]
always sets....
Upvotes: 5