I have two arrays in php as shown in the code
<?php
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
print_r(array_merge($a[0],$b[0]));
?>
I need to merge two arrays. array_merge function successfully merged two of them but key value gets changed. I need the following output
Array
(
[0]=>Array(
[500] => 1
[502] => 2
[503] => 3
[504] => 5
)
)
What function can I use in php so that the following output is obtained without changing key values?
From the documentation, Example #3:
If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator:
<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>
The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.
array(5) {
[0]=>
string(6) "zero_a"
[2]=>
string(5) "two_a"
[3]=>
string(7) "three_a"
[1]=>
string(5) "one_b"
[4]=>
string(6) "four_b"
}
Therefore, try: $a[0] + $b[0]
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
$c = $a + $b; //$c will be a merged array
see the answer for this question
Try:
$final = array();
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
foreach( $a as $key=>$each ){
$final[$key] = $each;
}
foreach( $b as $key=>$each ){
$final[$key] = $each;
}
print_r( $final );
$a=array('0'=>array('500'=>'1','502'=>'2'));
$b=array('0'=>array('503'=>'3','504'=>'5'));
$c = $a[0] + $b[0];
print_r($c);
Will print:
Array ( [500] => 1 [502] => 2 [503] => 3 [504] => 5 )
Just write :
<?php
$a = array(2=>'green', 4=>'red', 7=>'yellow',3=>'Green');
$b = array(8=>'avocado');
$d = $a+$b;
echo'<pre>'; print_r($d);
?>
out put :
Array
(
[2] => green
[4] => red
[7] => yellow
[3] => Green
[8] => avocado
)
Related
I have an array like this
$array = array( [0] => 'red1', [1] => 'blue1', [2] => 'red2', [3] => 'red3', [4] => 'blue2' );
A want to reverse order of elements with red value only so it looks like this:
$array = array( [0] => 'red3', [1] => 'blue1', [2] => 'red2', [3] => 'red1', [4] => 'blue2' );
I think a possible solution might be to:
Get all the values from the $array that you are looking for and
store them in an array $found
Reverse the values in $found keeping the keys
Replace the values in $array with the values from $found using
the key
For example:
$array = array(0 => 'red1', 1 => 'blue1', 2 => 'red2', 3 => 'red3', 4 => 'blue2');
// First get all the values with 'red' and store them in an array
$found = preg_grep('/red\d+/', $array);
// Reverse the values, keeping the keys
$found = array_combine(
array_keys($found),
array_reverse(
array_values($found)
)
);
// Then replace the values of $array with values having the same keys in $found
$array = array_replace($array, $found);
var_dump($array);
Will result in:
array(5) {
[0]=>
string(4) "red3"
[1]=>
string(5) "blue1"
[2]=>
string(4) "red2"
[3]=>
string(4) "red1"
[4]=>
string(5) "blue2"
}
You can catch red's quote to a new array and sort them.
<?php
$arr = array(
'red1',
'blue1',
'red2',
'red3',
'blue2'
);
$sortArr = array();
for ($i=0; $i < sizeof($arr); $i++) {
if(strstr($arr[$i], "red")){
$sortArr[] = &$arr[$i];
}
}
?>
I think you can do using searching specific words by strpos and sorting array by ksort (sort associative arrays in ascending order, according to the key)
foreach ($array as $key => $value) {
if(strpos($value,"red") !== false){
($key === 0) ? $index = 3 : (($key === 3) ? $index = 0 : $index = 2);
$temp[$index] = $value;
}
else {
$temp[$key] = $value;
}
}
ksort($temp);
var_dump($temp);
[But It will not work in larger array than this]
How to merge many Arrays in php
$array1="Array ( [0] => mouse ) Array ( [0] => mac ) Array ( [0] => keyboard )";
how i can array like this
Array( [0] =>mouse [1] => mac [2] =>keyboard );
depending on how your arrays are being stored, there are a couple of options.
Here are 2 examples:
<?php
$old_array = array(
array('mouse'),
array('mac'),
array('keyboard')
);
$new_array = array();
foreach($old_array as $a){
$new_array[] = $a[0];
}
echo '<pre>',print_r($new_array),'</pre>';
//// OR ////
$array1 = array('mouse');
$array2 = array('mac');
$array3 = array('keyboard');
$new_array = array_merge($array1,$array2,$array3);
echo '<pre>',print_r($new_array),'</pre>';
You should use array_merge function of PHP.
This:
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
will return this:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
It's as easy as a piece of cake! :)
Try it: http://www.w3schools.com/php/showphp.asp?filename=demo_func_array_merge
Tutorials:
http://www.w3schools.com/php/func_array_merge.asp
http://php.net/array_merge
So you basically have an array of arrays. You can do this in the following way:
$array = array(array(0 => 'mouse'), array(1 => 'mac'), array(2 => 'keyboard'));
$mergedArray = array();
foreach ($array as $part) {
$mergedArray = array_merge($mergedArray, $part);
}
var_dump($mergedArray);
The result is exactly what you would expect:
array(3) {
[0]=>
string(5) "mouse"
[1]=>
string(3) "mac"
[2]=>
string(8) "keyboard"
}
If you also have scalars in the big array, you can modify the loop to the following:
foreach ($array as $part) {
if (!is_array($part)) {
$mergedArray[] = $part;
} else {
$mergedArray = array_merge($mergedArray, $part);
}
}
Note: This will merge all values from all sub arrays, it's not limited to one entry per sub array.
php array_merge() function, 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.
Merge N number of array using $array = array_merge( $array1 , $array2, $array3 ..... $arrayN);
$array1 = array ( '0' => 'mouse' );
$array2 = array ( '0' => 'mac' );
$array3 = array ( '0' => 'keyboard' );
$array = array_merge( $array1 , $array2, $array3);
echo "<pre>";
print_r($array);
echo "</pre>";
O/P:
Array
(
[0] => mouse
[1] => mac
[2] => keyboard
)
More info: http://us2.php.net/array_merge
This question already has answers here:
Convert a comma-delimited string into array of integers?
(17 answers)
Closed 9 years ago.
Say I have a string like so $thestring = "1,2,3,8,2".
If I explode(',', $thestring) it, I get an array of strings. How do I explode it to an array of integers instead?
array_map also could be used:
$s = "1,2,3,8,2";
$ints = array_map('intval', explode(',', $s ));
var_dump( $ints );
Output:
array(5) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
[3]=> int(8)
[4]=> int(2)
}
Example codepad.
Use something like this:
$data = explode( ',', $thestring );
array_walk( $data, 'intval' );
http://php.net/manual/en/function.array-walk.php
For the most part you shouldn't really need to (PHP is generally good with handling casting strings and floats/ints), but if it is absolutely necessary, you can array_walk with intval or floatval:
$arr = explode(',','1,2,3');
// use floatval if you think you are going to have decimals
array_walk($arr,'intval');
print_r($arr);
Array
(
[0] => 1
[1] => 2
[2] => 3
)
If you need something a bit more verbose, you can also look into settype:
$arr = explode(",","1,2,3");
function fn(&$a){settype($a,"int");}
array_walk($f,"fn");
print_r($f);
Array
(
[0] => 1
[1] => 2
[2] => 3
)
That could be particularly useful if you're trying to cast dynamically:
class Converter {
public $type = 'int';
public function cast(&$val){ settype($val, $this->type); }
}
$c = new Converter();
$arr = explode(",","1,2,3,0");
array_walk($arr,array($c, 'cast'));
print_r($arr);
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 0
)
// now using a bool
$c->type = 'bool';
$arr = explode(",","1,2,3,0");
array_walk($arr,array($c, 'cast'));
var_dump($arr); // using var_dump because the output is clearer.
array(4) {
[0]=>
bool(true)
[1]=>
bool(true)
[2]=>
bool(true)
[3]=>
bool(false)
}
Since $thestring is an string then you will get an array of strings.
Just add (int) in front of the exploded values.
Or use the array_walk function:
$arr = explode(',', $thestring);
array_walk($arr, 'intval');
$thestring = "1,2,3,8,a,b,2";
$newArray = array();
$theArray = explode(",", $thestring);
print_r($theArray);
foreach ($theArray as $theData) {
if (is_numeric($theData)) {
$newArray[] = $theData;
}
}
print_r($newArray);
// Output
Original array
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 8 [4] => a [5] => b [6] => 2 )
Numeric only array
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 8 [4] => 2 )
$arr=explode(',', $thestring);
$newstr = '';
foreach($arr as $key=>$val){
$newstr .= $val;
}
I'm look to naturally sort an array, in reverse order and not preserve the keys. For example, I'd like this array:
[0] => 1-string
[1] => 2-string
[2] => 10-string
[3] => 4-srting
[4] => 3-srting
To end up like this:
[0] => 10-srting
[1] => 4-string
[2] => 3-string
[3] => 2-string
[4] => 1-string
I've got it close with usort($array, 'strnatcmp'); but it's not in reverse order. array_reverse() after doesn't help.
Any ideas?
I'm a bit puzzled about "array_reverse() after doesn't help." because
<?php
echo PHP_VERSION, "\n";
$x = array(
'1-string',
'2-string',
'10-string',
'4-srting',
'3-srting'
);
natsort($x);
$x = array_reverse($x, false);
print_r($x);
prints
5.3.8
Array
(
[0] => 10-string
[1] => 4-srting
[2] => 3-srting
[3] => 2-string
[4] => 1-string
)
on my machine
Use the $preserveKeys attribute of array_reverse() to reset the keys as well as reversing the array after a natcasesort().
function rnatcasesort(&$array) {
natcasesort($array);
$array = array_reverse($array, false);
}
$values = array('1-string', '2-string', '10-string', '4-string', '3-string');
rnatcasesort($values);
var_dump($values);
/*
array(5) {
[0]=>
string(9) "10-string"
[1]=>
string(8) "4-string"
[2]=>
string(8) "3-string"
[3]=>
string(8) "2-string"
[4]=>
string(8) "1-string"
}
*/
Use rsort() with the SORT_NATURAL flag.
rsort($array, SORT_NATURAL);
SORT_NATURAL was introduced in PHP 5.4. If you are on a lower version, go with the array_reverse(natsort()) version.
You could do
<?php
$arr = array("1-string", "2-string", "10-string","4-srting", "3-srting");
function sort_reverse($a, $b){
$a = (int)$a;
$b = (int)$b;
if ($a > $b){
return -1;
}
if ($a < $b){
return 1;
}
return 0;
}
usort($arr, "sort_reverse");
var_dump($arr);
pad here http://codepad.org/6dn81S3f
This works:
$array = array('1-string', '2-string', '10-string', '4-string', '3-string');
natsort($array);
$array = array_reverse($array);
print_r($array);
use this function to first do a natural sort and then by using array_reverse to make it in descending order
function natrsort($array)
{
natsort($array);
return array_reverse($array);
}
natrsort($array);
Doesn't rsort($array) fits your need?
I have two arrays. The first one looks like:
Array1
(
[14] => foo
[15] => bar
[16] => hello
}
and the sencond looks like:
Array2
(
[Label1] => foo
[Label2] => bar
[Label3] => hello
[Label4] => foo
[Label5] => bar
}
I would like to compare the values of array1 against array2, if they match, I would like to return the corresponding key of array2.
Any help will be appreciated. Thanks
You can use array_intersect to get the intersection of both arrays:
$arr1 = array(
14=>'foo',
15=>'bar',
16=>'hello'
);
$arr2 = array(
'Label1'=>'foo',
'Label2'=>'bar',
'Label3'=>'hello',
'Label4'=>'foo',
'Label5'=>'bar'
);
var_dump(array_intersect($arr2, $arr1));
This returns:
array(5) {
["Label1"]=>
string(3) "foo"
["Label2"]=>
string(3) "bar"
["Label3"]=>
string(5) "hello"
["Label4"]=>
string(3) "foo"
["Label5"]=>
string(3) "bar"
}
To get the keys of this resulting array, use array_keys. And if you want to get only the first key of each duplicate value, send it through array_unique first:
var_dump(array_keys(array_unique(array_intersect($arr2, $arr1))));
This will get you:
array(3) {
[0]=>
string(6) "Label1"
[1]=>
string(6) "Label2"
[2]=>
string(6) "Label3"
}
You can always use the infamous brute-force "for" iteration:
This gets you all the keys of the values that match. To get just the very first one you would do a simple modification of this code.
PHP Code:
$arr1 = array(
14=>'foo',
15=>'bar',
16=>'hello'
);
$arr2 = array(
'Label1'=>'foo',
'Label2'=>'bar',
'Label3'=>'hello',
'Label4'=>'foo',
'Label5'=>'bar'
);
$results = array();
foreach($arr1 as $val)
foreach($arr2 as $key=>$val2)
if($val == $val2) array_push($results, $key);
// or to get just the first,
// replace the if statement with
//
// if($val == $val2) {
// $result = $key;
// break 2;
// }
print_r($results);
Result is:
array(3) {
[0] => "Label1",
[1] => "Label2",
[2] => "Label3"
}
You can go about like this:
$array1 = array(14 => "foo", 15 => "bar", 16 => "hello");
$array2 = array("Label1" => "foo", "Label2" => "bar", "Label3" => "hello", "Label4" => "foo", "Label5" => "bar", "Label5" => "test");
$result = array_intersect($array2, $array1);
echo '<pre>';
print_r($result);
Output:
Array
(
[Label1] => foo
[Label2] => bar
[Label3] => hello
[Label4] => foo
)
More Info:
array_intersect
You might want to check array_intersect_assoc
<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);
?>
The above example will output:
Array
(
[a] => green
)
A simple loop will be much faster and cleaner than a cascade of built-in functions.
//$arr1, $arr2 as per Gumbo's answer...
$hash = array_flip($arr1);
$keys = array();
foreach($arr2 as $key => $val)
if(isset($hash[$val]))
$keys[] = $key;