Add additional data to array
I have associative array which looks like this.
$arr = array(
"FIRST" => 1,
"SECOND => 2,
"FOURTH => 4
);
The idea is how to "add" data to this array depending of expression. Here is what I'm trying to do:
if(3 == 3) {
$str = array("THIRD" => 3);
}
$arr = array(
"FIR开发者_如何学运维ST" => 1,
"SECOND => 2,
$str,
"FOURTH => 4
);
The problem is that the code above add $str as an array in $arr, not like "THIRD" => 3
What about http://php.net/manual/en/function.array-merge.php
Then you can merge the two arrays:
if(3 == 3) {
$str = array("THIRD" => 3);
}
$arr = array(
"FIRST" => 1,
"SECOND => 2,
"FOURTH => 4
);
$arr = array_merge($arr,$str);
But you can also do it on another way:
$arr = array(
"FIRST" => 1,
"SECOND => 2,
"FOURTH => 4
);
if(3 == 3) {
$arr["THIRD"]=3;
}
You must add the element after-the-fact:
$arr = array(
"FIRST" => 1,
"SECOND" => 2,
"FOURTH" => 4
);
if (someCondition) {
$arr["THIRD"] = 3;
}
You may want to sort the array afterwards.
Change the line in this condition as below. You do not need to create another array and put that array into original array. Just reference original array like below.
if(3 == 3) {
$arr["THIRD"]= 3;
}
The problem is -- as far as I can see -- that you want to create some sort of order in your array. While PHP can sort arrays it will not be able to handle what you are trying, because it doesn't know, that FIRST
has to come before SECOND
and so on. How to insert any kind of new data to the array the anwers above already tell you. array_merge()
is one of the best ways to deal with it, I think.
In order to do what you intend, you would need to implement a function, that can compare your keys and then use it with usort()
to create the intended order in your array. You could just add your new entry then and then recreate the intended order. From an effectiveness point of view this would be a rather bad idea though. If you intend to use this in a productive environment, you might want to consider spending more time on the matter and replace the whole thing with a properly implemented collection object, that can handle your key-value-pairs the way you want it.
You could check eval
function in PHP as described :
eval (PHP 4, PHP 5) eval — Evaluate a string as PHP code
<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>
this code will output :
This is a $string with my $name in it.
This is a cup with my coffee in it.
精彩评论