Find difference value from two array in php [duplicate] - php

This question already has answers here:
Compare two array and get all differences
(2 answers)
Closed last year.
I want to get difference value from array and also want to compare that difference value is from which array.
First Array => Variable : $first_array
Array {607,608,609}
Second Array => Variable : $second_array
Array {607,608,609,610}
want to get output like Difference value : 610...... From Array :- $second_array
How can i get ? please help me ....

You can use array_diff()
$result=array_diff($first_array,$second_array);
print_r($result);

Try this :
$first_array=array(607,608,609);
$second_array=array(607,608,609,610);
$result=calculate_diff($second_array,$first_array);
print_r($result);
function calculate_diff($array1,$array2)
{
$diff = [];
$larger_array = $array2;
$smaller_array = $array1;
if(count($array1) > count($array2))
{
$larger_array = $array1;
$smaller_array = $array2;
}
foreach($larger_array as $ele)
{
if(!in_array($ele,$smaller_array))
{
$diff[] = $ele;
}
}
return $diff;
}

it will work
<?php
$a=Array(607,608,609,610);
$b=Array (607,608,609);
$result=array_diff($a,$b);
print_r($result);
?>
or else try this
<?php
$array2 = array(607,608,609);
$array1 = array(607,608,609,275);
foreach ($array1 as $value)
{
if(in_array($value, $array2))
{
$key = array_search($value, $array2);
$key1 = array_search($value, $array1);
unset($array2[$key]);
unset($array1[$key1]);
//echo "yes<br>";
}
}
$merge = array_merge($array1,$array2);
print_r($merge);
?>

Use array_diff
<?php
$a=Array(607,608,609,610);
$b=Array (607,608,609);
$res=array_diff($a,$b);
print_r($res); // output 610
?>

Try this:
$a = array(607,608,609,610);
$b = array(607,608,609);
$c = array_diff($a,$b);
print_r($c);

Try This:
$a1=array(607,608,609,610);
$a2=array(607,608,609);
$result=array_diff($a1,$a2);
print_r($result);
Output :- Array ( [3] => 610 )

Try this by merging them and then using array_diff, array_diff_assoc and array_unique.
https://3v4l.org/Z1vpe
$first = Array(607,608,609,610);
$second = Array(800,607,608,609);
$Fcount = count($first);
$arr = array_merge($first, $second);
$arrc= array_diff($arr, array_diff_assoc($arr, array_unique($arr)));
foreach ($arrc as $key => $value){
if($key < $Fcount){
echo "first array ". $value . "\n";
}else{
echo "second array " . $value . "\n";
}
}
Edited to add how to find which array the value is in. https://3v4l.org/W7rch

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue","r"=>"black");
$d = array_merge($a1,$a2);
output:array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"red","f"=>"green","g"=>"blue","r"=>"black")
$result=array_diff($d,array_intersect($a2,$a1));
print_r($result);
output:array("d"=>"yellow","r"=>"black");

Related

PHP: Convert string into array

I have an input string that has the following value:
"[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]"
I want to convert this into a php array that looks something like this:
$date=2018-05-08;
$meal=1;
$option=17;
can someone help me please !
<?php
$data="[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]";
$data=explode(',',$data);
foreach($data as $row){
preg_match_all('#\[(.*?)\]#', $row, $match);
$date=$match[1][0];
$meal=$match[1][1];
$option=$match[1][2];
}
This will store the values you need into the variables. I would suggest to store them in arrays and not variables so you can handle them outside of the foreach loop but that's up to you.
Simple parser for You
$arr1 = explode (",","[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]"); // making array with elements like : [0] => "[2018-05-08][1][17]"
$arr2;
$i = 0;
foreach($arr1 as $item){
$temp = explode ("][",$item); // array with elements like [0] => "[2018-05-08", [1] => "1", [2] => "21]"
$arr2[$i]['date'] = substr( $temp[0], 1 ); // deleting first char( '[' )
$arr2[$i]['meal'] = $temp[1];
$arr2[$i]['option'] = substr($temp[2], 0, -1); // deleting last char( ']' )
$i++;
}
you cannot set array to variable .If you want convert string to array, i think my code example may help you:
$a= "[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]";
$b= explode(",",$a );
foreach ($b as $key =>$value) {
$b[$key] = str_replace("[", " ", $b[$key]);
$b[$key] = str_replace("]", " ", $b[$key]);
$b[$key] =explode(" ",trim($b[$key]) );
}
print_r($b);
$results = array_map(
function ($res) {
$res = rtrim($res, ']');
$res = ltrim($res, '[');
return explode('][', $res);
},
explode(',', $yourString)
);
//get variables for first element of array
list($date, $meal, $option) = $results[0];

how to remove empty array value with key in php?

I am getting an array similar to the following one.
{"form_data":["1","2","4","5","","6"],"final_data":["1","2","4","5","","6"]}
If form data values are null, I want to replace that key's value with the value of the next key.
Like above, after value 5, I have null values. It needs to be like this:
"final_data":["1","2","4","5","fill this with 6","remove this"]
"final_data":["1","2","4","5","6"] like this
I tried array_filter(), but it didn't help.
If the response is in json format then ...
$json = '{"form_data":["1","2","4","5","","6"],"final_data":["1","2","4","5","","6"]}';
$array = json_decode($json, TRUE);
foreach($array as $index => $a) {
$array[$index] = array_filter($a);
}
print_r($array);
https://eval.in/866379
Update:
foreach($array as $index => $a) {
$array[$index] = array_value(array_filter($a));
}
https://eval.in/866522
try following code,
foreach($myarray as $key=>$value)
{
if(is_null($value) || $value == '')
unset($myarray[$key]);
}
Try this array_filter() with array_map() and array_values()
<?php
$array = array("form_data" => array("1","2","4","5","","6"), "final_data" => array("1","2","4","5","","6"));
function filterMe($paraArr){
return array_values(array_filter($paraArr));
}
$array = array_map("filterMe",$array);
echo "<pre>";
print_r($array);
check the output here https://eval.in/866401

Compare Two Associative Array with different value

I have two Associative array.
$a1 = array("Peter"=>"a","Ben"=>"b","Joe"=>"c");
$a2 = array("Peter"=>"5","Joe"=>"15");
and Out put result should be...
a=5
b=null
c=15
foreach($a1 as $aKey => $aValue) {
echo $aValue, '=';
echo (isset($a2[$aKey])) ? $a2[$aKey] : 'null';
echo PHP_EOL;
}
foreach($a1 as $key => $value) {
echo $a1[$key].'='.$a2[$key];
}
You will get the output, but this have nothing to do with array comparing.

Increasing array elements while in foreach loop in php? [duplicate]

This question already has answers here:
How does PHP 'foreach' actually work?
(7 answers)
Closed 8 years ago.
Consider the code below:
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
?>
It is not displaying 'a'. How foreach works with hash-table(array), to traverse each element. If lists are implement why can't I add more at run time ?
Please don't tell me that I could do this task with numeric based index with help of counting.
Foreach copies structure of array before looping(read more), so you cannot change structure of array and wait for new elements inside loop. You could use while instead of foreach.
$arr = array();
$arr['b'] = 'book';
reset($arr);
while ($val = current($arr))
{
print "key=".key($arr).PHP_EOL;
if (!isset($arr['a']))
$arr['a'] = 'apple';
next($arr);
}
Or use ArrayIterator with foreach, because ArrayIterator is not an array.
$arr = array();
$arr['b'] = 'book';
$array_iterator = new ArrayIterator($arr);
foreach($array_iterator as $key=>$val) {
print "key=>$key\n";
if(!isset($array_iterator['a']))
$array_iterator['a'] = 'apple';
}
I think you need to store array element continue sly
Try
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'][] = 'apple';
}
print_r($arr);
?>
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
http://cz2.php.net/manual/en/control-structures.foreach.php
Try this:
You will get values.
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
echo '<pre>';
print_r($arr);
?>
Output:
key=>b
<pre>Array
(
[b] => book
[a] => apple
)
If you want to check key exist or not in array use array_key_exists function
Eg:
<?php
$arr = array();
$arr['b'] = 'book';
print_r($arr); // prints Array ( [b] => book )
if(!array_key_exists("a",$arr))
$arr['a'] = 'apple';
print_r($arr); // prints Array ( [b] => book [a] => apple )
?>
If you want to use isset condition try like this:
$arr = array();
$arr['b'] = 'book';
$flag = 0;
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr["a"]))
{
$flag = 1;
}
}
if(flag)
{
$arr['a'] = 'apple';
}
print_r($arr);
How about using for and realtime array_keys()?
<?php
$arr = array();
$arr['b'] = 'book';
for ($x=0;$x<count($arr); $x++) {
$keys = array_keys($arr);
$key = $keys[$x];
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}

How to get key of array when i know this value in php [duplicate]

This question already has answers here:
Retrieve array key passed on value PHP
(5 answers)
Closed 9 years ago.
I have an array like this:
$array = array('name'=>'Van Pham','age'=>'23','sex'=>'male');
How can I get key 'age' with value '23'?
you are looking for array_keys http://www.php.net/manual/en/function.array-keys.php
print_r(array_keys($array, "23")); // age
OR by HamZa DzCyberDeV
echo array_keys($array, "23")[0];
http://codepad.viper-7.com/bZErGT
try this
$my_arr = array('name'=>'Van Pham','age'=>'23','sex'=>'male');
echo get_array_by_value($my_arr, '23');
function get_array_by_value($my_arr = '', $arr_value = '') {
$new_arr = array_flip($my_arr);
if (isset($new_arr[$arr_value])) {
return $new_arr[$arr_value];
}
}
output
age
use array_search()
$key= array_search($value, $array);
example:
$array = array('name'=>'Van Pham','age'=>'23','sex'=>'male');
echo array_search("23", $array); //age
try this
<?php
$arr = array('name'=>'Van Pham','age'=>'23','sex'=>'male');
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
?>
I think you want to find the keys, for values 23, do it like this:
$array = array('name'=>'Van Pham','age'=>'23','sex'=>'male');
while ($value = current($array)) {
if ($value == '23') {
echo key($array)."\n";
}
next($array);
}
Try with
foreach($array as $key => $value)
{
if($key == 'age' && $value == '23')
echo $key.'-'.$value;
}
<?php
$array = array('name'=>'Van Pham','age'=>'23','sex'=>'male');
echo array_keys($array, "23") .":". $array['age'];
?>
Output
age : 23
It can be done easily using array_search function.This Function Searches the array for a given value and returns the corresponding key if successful.
<?php
$array = array('name'=>'Van Pham','age'=>'23','sex'=>'male');
$key1 = array_search('23', $array);
echo '<p>Key 1='.$key1.'</p>';
$key2 = array_search('Van Pham', $array);
echo '<p>Key 2='.$key2.'</p>';
$key3 = array_search('male', $array);
echo '<p>Key 3='.$key3.'</p>';
$key4 = array_search('female', $array);
echo '<p>Key 4='.$key4.'</p>';
?>
Output:
Key 1=age
Key 2=name
Key 3=sex
Key 4=
DEMO

Categories