How provide indexing to any array in php - php

i am trying to compare two arrays using php intersect function.
I am using following code
$input_array=array();
$input_array=explode("," , $_POST['list']);
$array = array();
$result1 =mysql_query("SELECT b_no FROM abc");
while($fetch_array=mysql_fetch_array($result1)){
$array[] = $fetch_array['b_no'];
}
$result=array_intersect($input_array,$array);
echo"<pre>";
print_r($result);
echo"</pre>";
and result is like this:
Array
(
[4] => 443829
[5] => 952040
)
The resultant array have not their own indexing. Is possible to provide indexing?

It is possible to provide indexing, but you will need to specify which indexing you want.
If the resulting indexing is not what you expected, please note that array_intersect() only compares the values of each array, and it retains the index or key from the first array of each match.
If your requirement is to also match on the keys of an associative array (although I am inferring you are not judging from your example) you can use array_intersect_assoc().
If you want to simply 'reset' the indexing you can use array_values(). For example:
<?php
$a = [2 => 1, 2, 3];
$b = [2, 3, 4];
$intersect = array_intersect($a, $b);
print_r($intersect);
// Original keys are retained:
//
// Array
// (
// [3] => 2
// [4] => 3
// )
print_r(array_values($intersect));
// Original keys are discarded:
//
// Array
// (
// [0] => 2
// [1] => 3
// )
On the other hand, if you had a specific set of keys you wanted to use, say for example ['foo', 'bar'] you can use array_combine() - it accepts two arrays, one as keys and the other as values, to explicitly define a new set of indexes or keys for an array. For example:
$keys = ['foo', 'bar'];
print_r(array_combine($keys, $intersect);
// Array
// (
// [foo] => 2
// [bar] => 3
// )
$indexes = [100, 200];
print_r(array_combine($indexes, $intersect));
// Array
// (
// [100] => 2
// [200] => 3
// )
Please note, array_combine() requires that the length of both arrays are the same. I cannot really provide any more detail unless you update your question but I hope this helps :)

Related

Combine dynamic arrays with dynamic keys in to single arrays

I have this dynamic multiple arrays that I need to combine in one array and serialized them. The problem is I need to keep both key and value.
$arr = array($bet_option_id => $bet_option_name);
Here i need to keep both bet_option_id AND bet_option_name. Then this result output:
Array ( [997650802] => Over 2.5 )
Array ( [997650807] => Yes )
This need to be simply
Array
(
[997650802] => Over 2.5
[997650807] => Yes
)
As it's dynamic, sometimes not comes with just single array so apparently I couldn't get it working. I need to retrieve both bet_option_id & bet_option_name. Tried something like this:
$arr = array($bet_option_id => $bet_option_name); //This is where all array keys, values are stores
$result = array();
foreach ($arr as $array) {
$result = array_merge($result, $array);
}
Any inputs will be nice.
Rather than create individual arrays like...
$arr = array($bet_option_id => $bet_option_name);
If you first create an empty array ( like you do with $result)
$arr = array();
and then add each item in using
$arr[$bet_option_id] = $bet_option_name;
Then you don't need to manipulate the array after - just create it as you want it in the first place.
You could either do like Nigel Ren suggested which is the most elegant solution
In case that you do not have arrays that their keys are entirely numeric you may use array_merge. The quote following is from PHP array-merge
Example #2 Simple array_merge() example
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
Don't forget that numeric keys will be renumbered!
Array
(
[0] => data
)
Alternatively you can always join arrays together like this
$a1 = [ 997650802 => 'Over 2.5' ];
$a2 = [ 997650807 => 'Yes' ];
var_dump( $a1 + $a2 ); // result is [997650802 => 'Over 2.5',997650807 => 'Yes']
You can check more about Array Types and Array Operators

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
)

php assoc array

I have two assoc array i want to creat one array out of that
E.g
a(a=>1
b=>3
f=>5
)
b(a=>4
e=>7
f=>9
)
output must be
c(
a=>1
b=>3
f=>5
a=>4
e=>7
f=>9
)
i am new in php
Use array_merge(). Your resulting array CAN NOT have more than one entry for the same key, so the second a => something will overwrite the first.
Use the + operator to return the union of two arrays.
The new array is constructed from the left argument first, so $a + $b takes the elements of $a and then merges the elements of $b with them without overwriting duplicated keys. If the keys are numeric, then the second array is just appended.
This ey difference of the + operator and the function, array_merge is that array merge overwrites duplicated keys if the latter arguments contain that key. The documentation puts it better:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
If the keys are different, then use array_merge()
<?php
$a1=array("a"=>"Horse","b"=>"Cat");
$a2=array("c"=>"Cow");
print_r(array_merge($a1,$a2));
?>
OUTPUT:
Array ( [a] => Horse [b] => Cat [c] => Cow )
If the keys are the same, then use array_merge_recursive()
<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>
OUTPUT:
Array
(
[color] => Array
(
[favorite] => Array
(
[0] => red
[1] => green
)
[0] => blue
)
[0] => 5
[1] => 10
)

Merging and array by value instead of key in PHP

I have two arrays of values that I would like to combine - but the only methods that PHP provides seem to combine by key instead of value. Here is a hack that I was able to use to get this to work, but I am wondering if there is a better method or a native function that I have missed. It's been a while since I last used arrays and it seems like there is an easy answer to this.
//Input arrays that we want to combine into one array
$array = array(2, 3, 4, 5);
$array2 = array(5, 6, 1);
//Flip values and keys
$array = array_flip($array);
$array2 = array_flip($array2);
//Combine array
$array3 = $array2 + $array;
//flip array keys back to values
$array3 = array_keys($array3);
//Optional sort
sort($array3);
print_r($array3);
Which returns the combined values of the two arrays:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
Not entirely sure what you are trying to accomplish. I am assuming you are trying to combine 2 arrays without having any duplicates. If this is the case then the following would work
$newarr = array_unique(array_merge($array, $array2));

What would be the best way to add two associative arrays such that duplicate values are not over written : `+` or `array_merge`? [duplicate]

This question already has answers here:
Merging two arrays with the "+" (array union operator) How does it work?
(9 answers)
Closed 9 years ago.
What is the best way to add two associative arrays such that duplicate values are not over written : + or array_ merge ?
I was pretty sure that using + operator I can add two associative arrays such that duplicate values are not over written but this Answer is saying something different and so am not sure if it is really true.
I would really appreciate if you can share some lights on how can we add two associative arrays such that duplicate values are not over written.
Appreciate your time and responses.
An array can't have more than one key-value pair with the same key. So if you have:
$array1 = array(
'foo' => 5,
'bar' => 10,
'baz' => 6
);
$array2 = array(
'x' => 100,
'y' => 200,
'baz' => 30
);
If you combine these arrays, you only get to keep one of the values of the combined array. The methods you describe do two different things:
print_r(($array1 + $array2));
// Result:
// Array
// (
// [foo] => 5
// [bar] => 10
// [baz] => 6
// [x] => 100
// [y] => 200
// )
print_r(array_merge($array1, $array2));
// Result:
// Array
// (
// [foo] => 5
// [bar] => 10
// [baz] => 30
// [x] => 100
// [y] => 200
// )
So you really need to define what you want to happen when you combine the arrays.
UPDATE
Based on #davidosomething's answer, here's what happens if you do array_merge_recursive():
print_r(array_merge_recursive($array1, $array2));
// Result:
// Array
// (
// [foo] => 5
// [bar] => 10
// [baz] => Array
// (
// [0] => 6
// [1] => 30
// )
//
// [x] => 100
// [y] => 200
// )
You actually want array_merge_recursive
This creates an array of arrays if the KEY is the same but the value is different
Both array_merge and union will DISCARD one of the VALUES if a duplicate key is found
If you want to keep both values, you have to change the key for at least one of them. Perhaps you can write your own method to merge two arrays which prefixes all keys.
array_merge will combine the arrays such that no values are lost, provided the arrays have contiguous numeric keys. If you start mixing string keys, values with the same keys will be overwritten. If you treat your arrays as arrays and not maps, array_merge will do what you want.
a picture is better than 1000 words
$a = array('foo' => 'A');
$b = array('foo' => 'B');
print_r($a + $b); // foo=A
print_r(array_merge($a, $b)); // foo=B

Categories