How can I get array like this - php

//I have array like below:
$a =array('1,2,6');
$b =array('2,3,1');
//Then I using ArrayCombine :
$arr_combine = array_combine( $a, $b );
//OUTPUT:
//Array( [1,2,6] => 2,3,1 ) ;
how can I get array like below?
//OUTPUT:
array( 1=>2, 2=>3, 6=>1 );

If you have the array like that, then you have to explode the element.
$result = array_combine(explode(',', $a[0]), explode(',', $b[0]));

It's taking as complete one string due to your present quotes in arrays,
Should be,
$a = array('1','2','6'); // And not '1,2,6'
$b = array('2','3','1');
$arr_combine = array_combine( $a, $b );
DEMO.
And if you can't change the array & have the format like that only see #xdazz answer.

For your second question check like this
<?php
$x = array( 1 => '2', 2 => '3', 6 => '1') ;
$y = array( 1 => '2', 6 => '2' ) ;
$s = array();
foreach($x as $key=>$val)
{
if (array_key_exists($key,$y))
{
$s[$key] = $x[$key] + $y[$key];
}
}
var_dump($s);
?>
Try like this
<?php
$a =array('1,2,6');
$b =array('2,3,1');
$a = explode(',',$a[0]);
$b = explode(',',$b[0]);
var_dump($a);
var_dump($b);
var_dump(array_combine($a,$b));
?>

Related

Implode columnar values between two arrays into a flat array of concatenated strings

I have two arrays, $array_A and $array_B. I'd like to append the first value from $array_B to the end of the first value of $array_A and repeat this approach for all elements in both arrays.
$array_A = ['foo', 'bar', 'quuz'];
$array_B = ['baz', 'qux', 'corge'];
Expected output after squishing:
['foobaz', 'barqux', 'quuzcorge']
array_merge($array_A, $array_B) simply appends array B onto array A, and array_combine($array_A, $array_B) sets array A to be the key for array B, neither of which I want. array_map seems pretty close to what I want, but seems to always add a space between the two, which I don't want.
It would be ideal for the lengths of each array it to be irrelevant (e.g. array A has five entries, array B has seven entries, extra entries are ignored/trimmed) but not required.
// updated version
$a = ['a', 'b', 'c'];
$b = ['d', 'e', 'f', 'g'];
print_r(array_map('implode', array_map(null, $a, $b)));
Probably the fastest code, but more verbose than other options.
//updated version
$array_A = ['foo', 'bar', 'quuz'];
$array_B = ['baz', 'qux', 'corge'];
for ($i = 0, $c = count($array_A); $i<$c; $i++) {
$result[$i] = $array_A[$i].$array_B[$i];
}
var_dump($result);
There isn't an array function in PHP that does exactly that. However, you can write one yourself, like this one:
function array_zip($a1, $a2) {
$out = [];
for($i = 0; $i < min(sizeof($a1), sizeof($a2)); $i++) {
array_push($out, $a1[$i] . $a2[$i]);
}
return $out;
}
So given these arrays and running it:
$a = ["foo", "bar"];
$b = ["baz", "qux"];
print_r(array_zip($a, $b));
You would get:
Array
(
[0] => foobaz
[1] => barqux
)
Try this:
$A = ['foo', 'bar'];
$B = ['baz', 'qux'];
function arraySquish($array)
{
$new = [''];
foreach($array as $val) {
$new[0] .= $val;
}
return $new;
}
$A = arraySquish($A);
$B = arraySquish($B);
echo '<pre>';
print_r($A);
print_r($B);
echo '</pre>';
PHP Fiddle here.
An explicit array_map:
<?php
$colours = ['red', 'white', 'blue'];
$items = ['robin', 'cloud', 'mountain'];
$squished =
array_map(
function($colour, $item) {
return $colour.$item;
},
$colours,
$items
);
var_export($squished);
Output:
array (
0 => 'redrobin',
1 => 'whitecloud',
2 => 'bluemountain',
)
If you want to only go as far as the smallest array, you could either return null if either entries are null, and then filter your result.
Or truncate the arrays to the same length:
$b = array_intersect_key($b, $a);
$a = array_intersect_key($a, $b);
Regardless of if both arrays have the same length or if one is longer than the other or in what order the arrays occur in, the following technique will "squish" the values into a flat array of strings.
array_map() only needs to be called once and implode()'s default "glue" string is an empty string -- so it can be omitted.
Code: (Demo)
$a = ['a', 'b', 'c'];
$b = ['d', 'e', 'f', 'g'];
var_export(array_map(fn() => implode(func_get_args()), $a, $b));
Or consolidate the column data with spread operator: (Demo)
var_export(array_map(fn(...$column) => implode($column), $a, $b));
Output:
array (
0 => 'ad',
1 => 'be',
2 => 'cf',
3 => 'g',
)

Call global dynamic variable from a function

Is there a way to call a dynamic variable within a function that was set up outside the function, such as making it a global variable.
$a = 'test'
$b = 'cat'
$c = 'dog'
debug_vars(['a', 'b', 'c']);
function debug_vars( $arr ) {
$display = array();
foreach($arr AS $v) {
GLOBAL ${$v};
$display[$v] = $v;
}
print_r($display);
}
I would like it to show an array of [ 'a' => 'test', 'b' => 'cat', 'c' => 'dog' ]
You are recreating the built in compact function, which already does what you want:
$a = 'test' ;
$b = 'cat' ;
$c = 'dog' ;
print_r(compact('a','b','c'));
//Array ( [a] => test [b] => cat [c] => dog )
http://php.net/manual/en/function.compact.php
You're almost there
$a = 'test';
$b = 'cat';
$c = 'dog' ;
debug_vars(['a', 'b', 'c']);
function debug_vars( $arr ) {
$display = array();
foreach($arr AS $v) {
GLOBAL ${$v};
$display[$v] = ${$v};
// ^---^--------------- use the global ?
}
print_r($display);
}
Output :
Array ( [a] => test [b] => cat [c] => dog )
Althought this is working as expected, I do not recommend you to use global variables. This may lead easily to unmaintainable code. Try using another approach than globals.
use $GLOBALS[]:
$display[$v] = $GLOBALS[$v];
-> http://php.net/manual/en/reserved.variables.globals.php
EDIT:
Using global $$v as mentioned in the other answers may have side effects if the var name is used locally.
You can use a variable variable with the $$ operator.
<?php
$a = 'test';
$b = 'cat';
$c = 'dog';
debug_vars(['a', 'b', 'c']);
function debug_vars( $arr ) {
$debug = array();
foreach($arr AS $v) {
if ($v != 'debug') {
GLOBAL $$v;
$debug[$v] = $$v;
}
}
print_r($debug);
}

Compare 2 arrays after removing the keys that does not exist in both using array functions

I have 2 arrays a and b which may or may not have similar values.
$a = array('id' => 1, 'name' => 'John Doe', 'age' => 35);
$b = array('name' => 'John Doe', 'age' => 35);
I need to check whether the keys that are there in both the arrays contains same values or not using the array functions itself. Please help me.
NB: Array $a is always the parent array. If any key has to be popped, it would be only from $a.
You can use the following comparison based on array_intersect_assoc:
$b == array_intersect_assoc($a, $b)
This will be true when all of the $b key/value pairs occur in $a, false otherwise.
Use this code:
Use: array_diff_key
Remove duplicate key:
<?php
$a = array('id' => 1, 'name' => 'John Doe', 'age' => 35);
$b = array('name' => 'John Doe', 'age' => 35);
$c = array_diff_key($a, $b);
print_r($c); //Array ( [id] => 1 )
?>
Get duplicate key:
Use: array_intersect_key
<?php
function array_duplicate_keys() {
$arrays = func_get_args();
$count = count($arrays);
$dupes = array();
// Stick all your arrays in $arrays first, then:
for ($i = 0; $i < $count; $i++) {
for ($j = $i+1; $j < $count; $j++) {
$dupes += array_intersect_key($arrays[$i], $arrays[$j]);
}
}
return array_keys($dupes);
}
print_r(array_duplicate_keys($a, $b)); //Array ( [0] => name [1] => age )
?>
Get duplicate key and value:
<?php
function get_keys_for_duplicate_values($my_arr, $clean = false) {
if ($clean) {
return array_unique($my_arr);
}
$dups = $new_arr = array();
foreach ($my_arr as $key => $val) {
if (!isset($new_arr[$val])) {
$new_arr[$val] = $key;
} else {
if (isset($dups[$val])) {
$dups[$val][] = $key;
} else {
$dups[$val] = array($key);
}
}
}
return $dups;
}
print_r(get_keys_for_duplicate_values($a, $b));
//Array ( [id] => 1 [name] => John Doe [age] => 35 )
?>
If $b can have keys not present in $a, you can use array_intersect_key two times, with arguments in reversed order and check if both results are the same:
$ab = array_intersect_key($a, $b);
$ba = array_intersect_key($b, $a);
$allValuesEqual = ($ab == $ba);
use this:"it compare both key and value"
$result=array_diff_assoc($a1,$a2); //<-Compare both key and value, gives new array
example:
$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$a2=array("a"=>"red","c"=>"blue","b"=>"pink");
$result=array_diff_assoc($a1,$a2);
print_r($result);
//result will be
Array ( [b] => green )

Two arrays to one

I have two arrays and I want one, can I add array 2 to array one?
$array1 = array("Germany" => 2, "Belgium"=> 3);
$array2 = array("France" => 4, "Italy"=> 5);
$final_array = {both arrays in one};
is this possible?
Yes, use the array_merge function, like this:
$final_array = array_merge($array1, $array2);
print_r($final_array);
When I run the above script it'll output:
Array (
[Germany] => 2
[Belgium] => 3
[France] => 4
[Italy] => 5
)
Take a quick read here: http://www.php.net/manual/de/function.array-merge.php
Use array_merge like
$final_arr = array_merge($array1 , $array2);
print_r($final_arr);
See this LINK for more
I would like to mention that on duplicated keys array_merge() returns the value from the second array. So, if you have different values with same keys - you should write your own function.
For example:
<?php
$a = array('rund' => '2', 'group' => '3', 'kupon' => 'utre', 'tralala' => 'shtur_kupon');
$b = array('grund' => '2', 'group' => 'ww', 'soup' => '1', 'tralala' => 'fd');
function two_arrays_merge_all_values(array $a, array $b) {
foreach ($b as $b_key => $b_value) {
$a_last_index = count($a);
$current_index = 1;
foreach ($a as $a_key => $a_value) {
if ($a_key === $b_key) {
$unique = uniqid();
$a[$b_key . '_' . $unique] = $b[$b_key];
unset($b[$b_key]);
break;
}
if ($current_index == $a_last_index) {
$a[$b_key] = $b[$b_key];
unset($b[$b_key]);
}
$current_index++;
}
}
return $a;
}

How to compare multidimensional array keys

What I'm trying to do is compare the keys of the second level of a multidimensional array. here's an example:
$data = array(
array(
$a => $b,
$c => $d
),
array(
$e => $f,
$g => $h
)
)
How would I compare $a & $e?
Here, knowing that they have the same size and you want to compare sorted keys:
<?php
$data_1 = array_keys($data[0]);
$data_2 = array_keys($data[1]);
$size = count($data_1);
for($i=0;$i<$size;$i++)
{
if($data_1[$i]<$data_2[$i])
{//do smth
}
}
?>
$keys0 = array_keys($data[0]);
$keys1 = array_keys($data[1]);
if ($keys0[0] == $keys1[0])
{
...
}

Categories