Add up content of array to another array in php - php

I want to have an array that contains a list of something, then I have another array that contains a list of something. I want to add those arrays up to each other.
For example, I have this
<?php
$greetings1 = array (
'a' => 'hello',
'b' => 'hi'
);
$greetings2 = array ('c' => 'hey',
'd' => 'greetings'
);
array_push($greetings1, $greetings2);
foreach($greetings1 as $a => $b) {
echo $a.' and '.$b."<br/>";
}
?>
I want it so that the output is:
a and hello
b and hi
c and hey
d and greetings
the real output of the php code above is:
a and hello
b and hi
0 and Array
So how do I properly add the two arrays up?
Thanks!

You can array_merge
<?php
$greetings1 = array(
'a' => 'hello',
'b' => 'hi',
);
$greetings2 = array(
'c' => 'hey',
'd' => 'greetings',
);
$greetings = array_merge($greetings1, $greetings2);
Which will output:
Array
(
[a] => hello
[b] => hi
[c] => hey
[d] => greetings
)

array_merge($greetings1, $greetings2);
array_push just adds an element at the end of the array (in that case another array).

You're looking for array_merge

Related

Can I display/convert an array to a one-line compact form?

If I run the code below:
$family = array ("father" => "Bill", "mother" => "Cathrine", "kids" => array("Adam", "Emma", "Nick"));
var_export($family);
.. it will result in the following output:
array (
'father' => 'Bill',
'mother' => 'Cathrine',
'kids' =>
array (
0 => 'Adam',
1 => 'Emma',
2 => 'Nick',
),
)
I wonder if there's a simple way to display the array in a more compact 1-line-form, like this (or similar):
[father: Bill, mother: Cathrine, kids: [0: Adam, 1: Emma, 2: Nick]]
Can it be done (e.g. using some kind of implode), or is the only solution to iterate through the arrays elements and generate a compact string?
Yes. You can use json_encode() function for this.
Read this https://www.php.net/manual/en/function.json-encode.php
Just try this:
$x = json_encode($family);
var_dump($x);

Converting single array into multi dimensional array (grouping ) based on key

Lets say I have the following array:
$arr = array("exercise__2" => "Then a set", "sets__2" => 3, "exercise__4" => "And finally a set", "sets__4" => 3);
What I'm now trying to do is to convert this array into a multidimensional array every time the number changes in the key.
I know we have to use explode("__", $key), but I can't work out how to convert it to a multidimensional array so it would appear something like the following:
Array
(
Array
(
[exercise__2] => Then a set
[sets__2] => 3
)
Array
(
[exercise__4] => And finally a set
[sets__4] => 3
)
)
I suspect it's not too difficult but I'm frying my brain trying to work it out.
Simple for loop should do it:
$arr = array("exercise__2" => "Then a set", "sets__2" => 3, "exercise__4" => "And finally a set", "sets__4" => 3);
foreach($arr as $k =>$v) {
$res[explode("__", $k)[1]][$k] = $v;
}
You can use array_values if you don't want the extra key in the upper array.
Live example: 3v4l
Array_chunk seems to be enough.
Array_chunk splits an array with n number of items.
The third argument is to preserve keys.
$arr = array("exercise__2" => "Then a set", "sets__2" => 3, "exercise__4" => "And finally a set", "sets__4" => 3);
$result = array_chunk($arr, 2, true);
print_r($result);
Output:
Array
(
[0] => Array
(
[exercise__2] => Then a set
[sets__2] => 3
)
[1] => Array
(
[exercise__4] => And finally a set
[sets__4] => 3
)
)
https://3v4l.org/s57ua

PHP sorting issue, arsort vs asort + array_reverse

I was recently working on one of the project euler problem sets and came across this strange issue. I've solved the problem correctly with the first solution, but I don't know why the other version does not work as expected.
Here is the code that works:
asort($card_count, SORT_NUMERIC);
$card_count = array_reverse($card_count, true);
And here is the code that does not:
arsort($card_count, SORT_NUMERIC);
This is the only line i change and it makes a huge difference in the end result. Any ideas whats up with this?
The issue arises with sorting equal values in the array. Take the array:
$arr = array(
'a' => 1,
'b' => 1,
'c' => 1,
'd' => 1
);
Calling asort($arr, SORT_NUMERIC) on this array will reverse the array. Hence, the lines of code:
asort($arr, SORT_NUMERIC);
$arr = array_reverse($arr, true);
will put the array back in the original order.
So, adding in one value that's higher with change the array as such:
$arr = array(
'a' => 1,
'b' => 1,
'c' => 2,
'd' => 1
);
asort($arr, SORT_NUMERIC);
$arr = array_reverse($arr, true);
will yeild:
Array
(
[c] => 2
[a] => 1
[b] => 1
[d] => 1
)
while
arsort($arr, SORT_NUMERIC);
will yeild:
Array
(
[c] => 2
[d] => 1
[b] => 1
[a] => 1
)
Hopefully this sheds some light on the issue ...

php put arrays in arrays

I want to push some items in one array, here is the structure:
$str = 'String';
$a = array('some', 'sub', 'page');
and I want to push the items to some other array that should become:
Array (
[some] => Array (
[sub] => Array (
[page] => String
)
)
)
I don't know how exactly to explain it, so hope the example shows you something.
I want any new element in the first array (a) to be pushed as sub-array of the prevous one and the last to have the value from $str;
$string = 'My Value';
$my_first_array = array('my', 'sub', 'arrays');
Then some function to parse $my_first_array and transfer it as:
Example:
ob_start('nl2br');
$my_parsed_sub_array = parse_sub_arrays($my_first_array, $string);
print_r($my_parsed_sub_array);
===>>>
Array (
[my] => Array (
[sub] => Array (
[arrays] => String
)
)
)
[Edit] I hope that, this time, I've understood the question...
If you have your string and array like this :
$str = 'test';
$a = array('some', 'sub', 'page');
You could first initialize the resulting array this way, dealing with that special case of the last item :
$arr = array($a[count($a)-1] => $str);
Then, you can loop over each item of your $a array, starting from the end (and not working on the last item, which we've dealt with already) :
for ($i=count($a) - 2 ; $i>=0 ; $i--) {
$arr = array($a[$i] => $arr);
}
With this, dumping the resulting array :
var_dump($arr);
Should get you the expected result :
array
'some' =>
array
'sub' =>
array
'page' => string 'test' (length=4)
Old answer below, before understanding the question :
You could declare your array this way :
$arr = array(
'some' => array(
'sub' => array(
'page' => $str,
),
),
);
Or, using several distinct steps (might be easier, depending on the way you construct your sub-arrays, especially in a more complex case than the current example) :
$sub2 = array('page' => $str);
$sub1 = array('sub' => $sub2);
$arr = array('some' => $sub1);

insert value at the beginning of an array in php

my array is
$hello= array( Code => 'TIR', Description => 'Tires', Price => 100 )
now i want to add a value in array beginning of an array not the end of an array.... and results i want is
$hello= array( ref=>'World', Code => 'TIR', Description => 'Tires', Price => 100 )
UPDATE
actually i need any value that is coming will be added in the beginning of an array....this is not single value.. ref=world.... this is coming from output...like if i add quantity=50, then it should be added beginning of an array before 'ref' an array should be
$hello= array(quantity=>'50', ref=>'World', Code => 'TIR', Description => 'Tires', Price => 100 )
I would use array_merge()
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
$hello = array ("Code" => "Tir" .....); // you should really put quotes
// around the keys!
$world = array ("ref" => "World");
$merged = array_merge($world, $hello);
You can use the + operator:
$hello = array( 'Code' => 'TIR', 'Description' => 'Tires', 'Price' => 100 );
$hello = array('ref' => 'World') + $hello;
print_r($hello);
would give
Array
(
[ref] => World
[Code] => TIR
[Description] => Tires
[Price] => 100
)
Like Pekka said, you should put quotes around the keys. The PHP manual explicitly states omitting quotes is wrong usage. You might also want to check out my answer about the difference between using the + operator vs using array_merge to decide which you want to use.
$a= array( 'a' => 'a' );
$b = array( 'b' => 'b' );
$res = $b + $a;
//result: ( 'b' => 'b', 'a' => 'a' )
$hello = array_merge(array('ref'=>'World'), $hello);

Categories