PHP Array - brackets - php

does someone know the meaning of the [ ] in the creation of a PHP array, and if it's really needed. Becasuse from my point of view. Both ways are sufficinent
Way 1, with brackets:
$cars[] = array ('expensive' => $BMW,
'medium' => $Volvo,
'cheap' => $Lada);
Way2, without brackets:
$cars = array ('expensive' => $BMW,
'medium' => $Volvo,
'cheap' => $Lada);

Read http://php.net/manual/en/function.array-push.php for a clear answer as to the differences.
main differences:
citing array() can only be done when creating the variable.
$var[] can add values to arrays that already exist.
$var[] will create an array and is in effect the same function call as $var = array(...);
also
You can not assign multiple values in a single declaration using the $var[] approach (see example 4, below).
some work throughs:
1) Using array()
$cars = "cats";
$cars = array("cars","horses","trees");
print_r($cars) ;
Will output
$cars --> [0] = cars
[1] = horses
[2] = trees
2) Appending Values
Then writing $cars = array("goats"); will NOT append the value but will instead initialise a NEW ARRAY, giving:
$cars --> [0] = goats
But if you use the square brackets to append then writing $cars[] = "goats" will give you :
$cars --> [0] = cars
[1] = horses
[2] = trees
[3] = goats
Your original question means that whatever is on the right hand side of the = sign will be appended to current array, if the left hand side has the syntax $var[] but this will be appended Numerically. As shown above.
You can append things by key name by filling in the key value: $cars['cheap'] = $Lada; .
Your example 1 is setting that an array is held within an array, so to access the value $Lada you would reference $cars[0]['cheap'] . Example 2 sets up the array but will overwrite any existing array or value in the variable.
3) String And Numerical Indexing
The method of using the array(...) syntax is good for defining multiple values at array creation when these values have non-numeric or numerically non-linear keys, such as your example:
$cars = array ('expensive' => "BMW",
'medium' => "Volvo",
'cheap' => "Lada");
Will output at array of:
$cars --> ['expensive'] = BMW
['medium'] = Volvo
['cheap'] = Lada
But if you used the alternative syntax of:
$cars[] = "BMW";
$cars[] = "Volvo";
$cars[] = "Lada";
This would output:
$cars --> [0] = BMW
[1] = Volvo
[2] = Lada
4) I'm still writing....
As another example: You can combine the effects of using array() and $var[] with key declarations within the square brackets thus:
$cars['expensive'] = "BMW";
$cars['medium'] = "Volvo";
$cars['budget'] = "Lada";
giving:
$cars --> ['expensive'] = BMW
['medium'] = Volvo
['cheap'] = Lada
(my original answer was verbose and not very great).
5) Finally.....
So what happens when you combine the two styles, mixing the array() declaration with the $var[] additions:
$ray = array("goats" => "horny", "knickers" => "on the floor", "condition" => "sour cream");
$ray[] = "crumpet";
$ray[] = "bread";
This will maintain both numeric and string key indexes in the array, outputting with print_r():
$ray --> [goats] => horny
[knickers] => on the floor
[condition] => sour cream
[0] => crumpet
[1] => bread

They are different. The first one is an array inside of another one
$cars[] = array ('expensive' => "BMW",
'medium' => "Volvo",
'cheap' => "Lada");
var_dump($cars);
array (size=1)
0 =>
array (size=3)
'expensive' => string 'BMW' (length=3)
'medium' => string 'Volvo' (length=5)
'cheap' => string 'Lada' (length=4)
The second one is just an array
$cars = array ('expensive' => "BMW",
'medium' => "Volvo",
'cheap' => "Lada");
var_dump($cars);
array (size=3)
'expensive' => string 'BMW' (length=3)
'medium' => string 'Volvo' (length=5)
'cheap' => string 'Lada' (length=4)

way 1 results an array with array values (array of array)
whereas way2 is array which contains mentioned values

Way 1 adds your new array() at the end of the existing array. So if you have 2 elements inside that array already, a third one with the array you specified will be created.
Way 2 is the typical array creation - just that some other variables are used to fill the fields.
Simply to complete your exercise, here is way 3:
$arr = array();
$arr[1] = array("foo"=>"bar");
This puts the foo:bar array at entry #1 into the $arr variable.

The second example is clear. In the first example you are adding an array element without specifying its key, hence the empty brackets []. As the array is not yet initialized, its created at the same time. The result is, as others already pointed out, a multidimensional array.
Beware though that the first way is not encouraged:
If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment.
If $cars was already set, e.g. to a string, you would get an error.
$cars = 'test';
$cars[] = array ('expensive' => $BMW,
'medium' => $Volvo,
'cheap' => $Lada);

Method 1, with brackets: Multidimensional array
Array ( [0] => Array ( [expensive] => 12 [medium] => 13 [cheap] => 14 ) )
Method 2, with brackets: Associative array
Array ( [expensive] => 12 [medium] => 13 [cheap] => 14 )

Related

merge two associative arrays in one associative array

I want to merge many different assoc arrays in one array but in the form of assoc array. Like i have different arrays like this
Array ( [0] => abc [1] => def [2] => ghi )
Array ( [0] => jkl [1] => mno [2] => pqr )
.
.
.
and want to make an array like
array
0 =>
array
0 => string 'abc'
1 => string 'def'
2 => string 'ghi'
1 =>
array
0 => string 'jkl'
1 => string 'mno'
2 => string 'pqr'
.
.
.`
.
i am getting these arrays from a csv file. Please help. Thanks
If I understand correctly, you don't want to merge the arrays... you just want to make a multidimensional array i.e. an array of arrays. See the difference here.
You are creating the initial arrays from the csv file, but I'll create them here for completeness:
$array1 = array ( "0" => "abc", "1" => "def", "2" => "ghi" );
$array2 = array ( "0" => "jkl", "1" => "mno", "2" => "pqr" );
Then all you need to do is create an array with those arrays as the values, depending on what works with the rest of your code, e.g.
$multiarray = array();
$multiarray["0"] = $array1;
$multiarray["1"] = $array2;
or
$multiarray = array ( "0" => $array1, "1" => $array2 );
If you print_r ($multiarray);, it will look like the example in your question.
By the way, the examples you have given are not associative arrays, but I've treated them as if they are in case you do actually need them.
If your arrays are just standard indexed arrays, then you don't need to specify the key, e.g.
$array1 = new array("abc", "def", "ghi");
etc
$multiarray[] = $array1;
$multiarray[] = $array2;
I provide another point of view, which is lest optimized for the task in itself as I see it but might be useful in some context.
$array = array('abc', 'def', 'ghi');
$array2 = array('jkl', 'mno', 'pqr');
function gather(... $array){return $array;}
my_print_r(gather($array, $array2));
That function uses the splat operator, which natively gathers whatever arguments are sent to the function as entries in an array, called array in that example. We can do whatever we want with array in that function, but just by retuning it, it does what you asked for.

How to keep the previous values in array after new assignment?

I have an array named $arr = array. Some of its keys has value, like this:
$arr['1'] = 'one';
$arr['2'] = 'two';
$arr['3'] = 'three';
Now I initialize that array with another arry, some thing like this:
$arr = array('4' => 'four', '5' => 'five');
But I need to keep the previous values. I mean is, when I print that array, the output will be like this:
echo '<pre>';
print_r($arr);
/* ---- output:
Array
(
[4] => four
[5] => five
)
*/
While I want this output:
Array
(
[1] => one
[2] => two
[3] => three
[4] => four
[5] => five
)
So, How can I take care of old keys (values) after re-initialized?
Here are your options detailed below: array_merge, union (+ operator), array_push, just set the keys directly and make a function that just loops over the array with your own custom rules.
Sample data:
$test1 = array('1'=>'one', '2'=>'two', '3'=>'three', 'stringkey'=>'string');
$test2 = array('3'=>'new three', '4'=>'four', '5'=>'five', 'stringkey'=>'new string');
array_merge (as seen in other answers) will re-index numeric keys (even numeric strings) back to zero and append new numeric indexes to the end. Non numeric string indexes will overwrite the value where the index exists in the former array with the value of the latter array.
$combined = array_merge($test1, $test2);
Result (http://codepad.viper-7.com/c9QiPe):
Array
(
[0] => one
[1] => two
[2] => three
[stringkey] => new string
[3] => new three
[4] => four
[5] => five
)
A union will combine the arrays but both string and numeric keys will be handled the same. New indexes will be added and existing indexes will NOT be overwritten.
$combined = $test1 + $test2;
Result (http://codepad.viper-7.com/8z5g26):
Array
(
[1] => one
[2] => two
[3] => three
[stringkey] => string
[4] => four
[5] => five
)
array_push allows you to append keys to an array. So as long as the new keys are numeric and in sequential order, you can push on to the end of the array. Note though, non-numeric string keys in the latter array will be re-indexed to the highest numeric index in the existing array +1. If there are no numeric keys, this would be zero. You would also need to reference each new value as a separate argument (see arguments two and three below). Also, since the first argument is taken in by reference, it will modify the original array. The other options allow you to combine to a separate array in case you need the original.
array_push($test1, 'four', 'five');
Result (http://codepad.viper-7.com/5b9nvC):
Array
(
[1] => one
[2] => two
[3] => three
[stringkey] => string
[4] => four
[5] => five
)
You could also just set the keys directly.
$test1['4'] = 'four';
$test1['5'] = 'five';
Or even just make a loop and wrap it in a function to handle your custom rules for merging
function custom_array_merge($arr1, $arr2){
//loop over array 2
foreach($arr2 as $k=>$v){
//if key exists in array 1
if(array_key_exists($arr1, $k)){
//do something special for when key exists
} else {
//do something special for when key doesn't exists
$arr1[$k] = $v;
}
}
return $arr1;
}
The function could be expanded to use stuff like func_get_args to allow any number of arguments.
I'm sure there are also more "hacky" ways to do it using stuff like array_
splice or other array functions. However, IMO, I would avoid them just to keep the code a little more clear about what you are doing.
use array_merge:
$arr = array_merge($arr, array('4' => 'four', '5' => 'five'));
Well, as per the comments (which are correct) this will reindex the array, another solution to avoid that would be to do as follows:
array_push($arr, "four", "five");
But this would not work if you have different keys, like strings that are not masked numbers.
Another way is to use + in order to merge them maintaining keys:
$arr['1'] = 'one';
$arr['2'] = 'two';
$arr['3'] = 'three';
$arr2 = array('4' => 'four', '5' => 'five');
$arr = $arr + $arr2;
Another way to do it, and keeps the keys of the array, is using array_replace.
$arr['1'] = 'one';
$arr['2'] = 'two';
$arr['3'] = 'three';
print_r(array_replace($arr, array('4' => 'four', '5' => 'five')));
Output:
Array
(
[1] => one
[2] => two
[3] => three
[4] => four
[5] => five
)

Array in array in array

I'm a bit struggling with the associative arrays in associative arrays. Point is that I always have to drill deeper in an array and I just don't get this right.
$array['sections']['items'][] = array (
'ident' => $item->attributes()->ident,
'type' => $questionType,
'title' => $item->attributes()->title,
'objective' => (string) $item->objectives->material->mattext,
'question' => (string) $item->presentation->material->mattext,
'possibilities' => array (
// is this even neccesary to tell an empty array will come here??
//(string) $item->presentation->response_lid->render_choice->flow_label->response_label->attributes()->ident => (string) $item->presentation->response_lid->render_choice->flow_label->response_label->material->mattext
)
);
foreach ($item->presentation->response_lid->render_choice->children() as $flow_label) {
$array['sections']['items']['possibilities'][] = array (
(string) $flow_label->response_label->attributes()->ident => (string) $flow_label->response_label->material->mattext
);
}
So 'possibilities' => array() contains an array and if I put a value in it like the comment illustrates I get what I need. But an array contains multiple values so I am trying to put multiple values on the position $array['sections']['items']['possibilities'][]
But this outputs that the values are stores on a different level.
...
[items] => Array
(
[0] => Array
(
[ident] => SimpleXMLElement Object
(
[0] => QTIEDIT:SCQ:1000015312
)
[type] => SCQ
...
[possibilities] => Array
(
)
)
[possibilities] => Array
(
[0] => Array
(
[1000015317] => 500 bytes
)
[1] => Array
...
What am trying to accomplish is with my foreach code above is the first [possibilities] => Array is containing the information of the second. And of course that the second will disappear.
Your $array['sections']['items'] is an array of items, so you need to specify which item to add the possibilities to:
$array['sections']['items'][$i]['possibilities'][]
Where $i is a counter in your loop.
Right now you are appending the Arrays to [items]. But you want to append them to a child element of [items]:
You do:
$array['sections']['items']['possibilities'][] = ...
But it should be something like:
$array['sections']['items'][0]['possibilities'][] = ...
$array['sections']['items'] is an array of items, and as per the way you populate the possibilities key, each item will have it's own possibilities. So, to access the possibilities of the item that is being looped over, you need to specify which one from $array['sections']['items'] by passing the index as explained in the first answer.
OR
To make things simpler, you can try
Save the item array (RHS of the first =) to a separate variable instead of defining and appending to the main array at the same time.
Set the possibilities of that variable.
Append that variable to the main $array['sections']['items']
I have:
array[{IsChecked: true, SEC: 0, STP: 0},
{IsChecked: ture ,SEC: 0, STP: 1},
{IsChecked: false, SEC: 1 ,STP: 0}]
How to get each SEC where IsCheked value is true?

I am so confused with associative arrays in php (two and 3 dimensional)

I am learning php. In spite of so many examples on google, I am still confused about implementing arrays which are two dimensional and three dimensional. Can anyone explain, in simple terms, with an example please?
The easiest example for me was thinking of a SQL table as a multidimensional array.
The table might look like this:
ID | Name | Email
--------------------------
1 | John | john#email.com
2 | Jane | jane#email.com
And the array might look like this:
Array
(
[0] => Array
(
[0] => 1
[1] => John
[2] => john#email.com
)
[1] => Array
(
[0] => 2
[1] => Jane
[2] => jane#email.com
)
)
The table is turned into an array of arrays. Where each row is accessed by the first index and each column by the second index.
So If I wanted to get "Jane" I would use $array[1][1]
An associative array of that same table might look like this:
Array
(
[0] => Array
(
[ID] => 1
[Name] => John
[Email] => john#email.com
)
[1] => Array
(
[ID] => 2
[Name] => Jane
[Email] => jane#email.com
)
)
You would access "Jane" like $array[1]["Name"]
These are arrays which are nested in other arrays. Depending on how deep they are nested determines what dimensional they are.
Here is an example of a 1D and 2D array, respectively.
$arr =
array(
'item1' => 543,
654 => true,
'xas' => 0.54
);
// Accessing $arr[654] (returns true)
$arr2 = array(
array
(
'a' => 54,
'b' => 'Hello'
),
array
(
'itemx' => true,
954 => 'hello'
)
);
// Accessing $arr[0]['b'] (equal to 'Hello')
For a 3D array, you simply add another nested array into one of the 2nd level array items in the 2D array example.
There also is a very simple way to get started with multidimensional arrays.
Simply take a sheet and a pencil and start writing your multidimensional array down on paper first. It will help you a lot in the beginning.
It should look something like this.
ARRAY0 {
key0.0 => "value0.0",
key0.1 => "value0.1",
key0.2 => ARRAY1 {
key1.0 => "value1.0",
key1.1 => ARRAY2 {
key2.0 => "value2.0",
key2.1 => "value2.1",
},
key1.2 => "value1.2",
},
key0.3 => "value0.3",
};
This is just my way of visualizing the arrays you can come up with your own syntax if you want.
An array can have anything in it, from an integer to a string, to a full blown object, to another array.
Any array on its own is called a 1-dimensional array. If you think of it as a row of boxes, then it's a single row. If an array has another array in it then it's a 2-dimensional array: one of its boxes will be a column, adding another dimension.
$users = array() ;
$jim = array('Jim', 'Smith') ;
$users[] = $jim ;
//or in one step
$users = array(array('Jim', 'Smith')) ;
//then to access the first user:
$jim = $users[0];
//and his firstname:
$jimsname = $users[0][0] ;
//or
$jimsname = $jim[0] ;
You can access elements of the array and its nested arrays by indices, but you need to remember which numeric index corresponds to which piece of information. That's where you can use associative arrays, where the numeric indices are replaced by unique descriptive strings:
$users = array() ;
$jim = array(
'firstname' => 'Jim',
'lastname' => 'Smith'
) ;
$users['jim'] = $jim ;
//then to access jim:
$jim = $users['jim'];
//and his firstname:
$jimsname = $users['jim']['firstname'] ;
//or
$jimsname = $jim['firstname'] ;
That's pretty much it. You can see more here and in the manual
try this simply.
$anArray['abc'][1]['qwe']='this is a value';
$anArray['abc']['avs']='another value';
echo $anArray['abc'][1]['qwe'];
echo $anArray['abc']['avs'];
/*
Array is a bit different in PHP. You can think of array elements as single variables ($anArray['abc'][1]['qwe'] or $anArray['abc']['avs']). And you can create them like single variables. This is an addition to conventional arrays. Conventional way is also supported.
But what happens if you write : $anArray['abc']='something else';
$anArray['abc'] is just a string variable from that point. So you cannot (or may not as I didn't test it yet and practically everything is possible) access $anArray['abc'][1]['qwe'] anymore.
So try to think the elements like variables, first ;)
*/

PHP - How can I assign a name to my array key instead of an int with array_push

Hey everyone, I have a database result that returns from a method. I need to push 4 more values onto the stack but I need to name the keys. array_push() automatically assigns an int. How can I overcome this behavior?
Array
(
[these] => df
[are] => df
[the] => sdf
[keys] => sd
[ineed] => daf
[0] => something
[1] => something
[2] => something
[3] => something
)
The keys that are int values need to be changed. How can I do this using array_push?
Just like this:
$arr['anotherKey'] = "something";
$arr['yetAnotherKey'] = "something";
$arr['andSoOn'] = "something";
or
$arr = array_merge($arr, array(
'anotherKey' => "something",
'yetAnotherKey' => "something",
'andSoOn' => "something"
));
...but I'd recommend the first method, since it merely adds more elements to the array, whereas the second will have a lot more overhead (though it's much more flexible in some situations).
If the four values you want to use are already in an associative array themselves, you can use + to merge the two arrays:
$array1 = array('these' => ..., 'are' => .., 'keys' => ...);
$four_entries = array('four' => ..., 'more' => ..., 'keys' => ..., '!' => ...);
$merged_array = $array1 + $four_entries;
Why not
$arr["whateveryouwant"] = something
Note: If you use array_push() to add
one element to the array it's better
to use $array[] = because in that way
there is no overhead of calling a
function.
If you want to add more entries to the array, all you need to do is:
Existing array;
$array =
{
"these" => "df"
"are" => "df"
"the" => "sdf"
"keys" => "sd"
"ineed" => "daf"
}
Adding to the array
$array["new_key1"] = "something";
$array["new_key2"] = "something";
If you want to assign the name you do not use the array_push function, you just assign the element:
$array['somekey'] = 'somevalue';
So, in short, you can't do that using array_push.

Categories