PHP array comparison and finding matched and non matched items - php

I have been using this script for finding matched and nonmatched array items.
My code is.
$filter1 = "red,green,blue,yellow";
$parts1 = explode(',', $filter1);
$filter2 = "red,green,blue";
$parts2 = explode(',', $filter2);
for($i=0; $i< count($parts1); $i++)
{
for($j=0; $j< count($parts2); $j++)
{
if($parts1[$i] == $parts2[$j])
{
$match[] = $parts1[$i];
} else {
$nomatch[] = $parts1[$i];
}
}
}
print_r($match);
echo "<br>";
print_r($nomatch);
By using this code i am only getting the matched items and not nonmatched. Can anybody help.
Thanks in advance.

You can try using array_intersect and array_diff
$filter1 = "red,green,blue,yellow";
$parts1 = explode(',', $filter1);
$filter2 = "red,green,blue";
$parts2 = explode(',', $filter2);
$match = array_intersect($parts1, $parts2);
$nomatch = array_diff($parts1, $parts2);
var_dump($match,$nomatch);
Output
array
0 => string 'red' (length=3)
1 => string 'green' (length=5)
2 => string 'blue' (length=4)
array
3 => string 'yellow' (length=6)

this can be done by array_intersect and array_diff
$filter1 = "red,green,blue,yellow";
$parts1 = explode(',', $filter1);
$filter2 = "red,green,blue";
$parts2 = explode(',', $filter2);
$result = array_intersect($parts1 , $parts2 );
print_r($result);
Live Example
and
$result = array_diff($parts1 , $parts2 );
print_r($result);
LIVE example

because your nested loop not run at yellow color time
try this
$filter1 = "red,green,blue,yellow";
$filter2 = "red,green,blue,gray";
or
for($j=0; $j<= count($parts2); $j++)

$filter1 = "red,green,blue,yellow";
$parts1 = explode(',', $filter1);
$filter2 = "red,green,blue";
$parts2 = explode(',', $filter2);
$match = array();
$nomatch = array();
foreach($parts1 as $v){
if(in_array($v,$parts2))
$match[]=$v;
else
$nomatch[]=$v;
}

try this
$filter1 = "red,green,blue,yellow";
$parts1 = explode(',', $filter1);
$filter2 = "red,green,blue";
$parts2 = explode(',', $filter2);
foreach($parts1 as $first)
{
if(in_array($first, $parts2))
{
$match[] = $first;
}
else
{
$nomatch[] = $first;
}
}
print_r($match);
echo "<br>";
print_r($nomatch);
or you can use array_diff to get non matched items
print_r(array_diff($parts1,$parts2));
and for matched items use
print_r(array_intersect($parts1,$parts2));

Try the below code
$filter1 = "red,green,blue,yellow";
$parts1 = explode(',', $filter1);
$filter2 = "red,green,blue,purple";
$parts2 = explode(',', $filter2);
$matching = array_intersect($parts1, $parts2);
$non_matching = array_diff(array_merge($parts1, $parts2), $matching);
Changing your code, which should have similar result for non-matching as array_diff($parts1, $parts2);
for($i=0; $i< count($parts1); $i++)
{
$is_matching = false;
for($j=0; $j< count($parts2); $j++)
{
if($parts1[$i] == $parts2[$j])
{
$is_matching = true;
break;
}
}
if ($is_matching) {
$match[] = $parts1[$i];
} else {
$nomatch[] = $parts1[$i];
}
}

You can find matching value using array_intersect and non matching value using array_diff.
Here you can see LIVE DEMO
/**
* #param $arr
*/
function pr($arr)
{
echo '<pre>';
print_r($arr);
echo '</pre>';
}
$filter1 = "red,green,blue,yellow";
$parts1 = explode(',', $filter1);
$filter2 = "red,green,blue";
$parts2 = explode(',', $filter2);
$match = array_intersect($parts1, $parts2);
$nomatch = array_diff($parts1, $parts2);
pr($match);
pr($nomatch);
Output Screen:
Array
(
[0] => red
[1] => green
[2] => blue
)
Array
(
[3] => yellow
)

Related

How To convert array in string like to concate string with first array word like array[0].'->'.array[1]

$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
'Users->User Departments->Department Hierarchy',
'Settings->Registrar->Finance',
'Logs->Second Opinion Log'];
This is array and I want to convert it into string like below
The string should be one it just concate in one string.
Governance->Policies
Governance->Prescriptions
Governance->CAS Alerts
Users->User Departments
Users->Department Hierarchy
Settings->Registrar
Settings->Finance
Logs->Second Opinion Log
$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
'Users->User Departments->Department Hierarchy',
'Settings->Registrar->Finance',
'Logs->Second Opinion Log'];
$temp = '';
for($i = 0; $i < count($arr); $i++){
$arrVal = [];
$arrVal = explode('->',$arr[$i]);
if(count($arrVal) > 1){
for($j=0; $j < count($arrVal); $j++){
if($j == 0){
$temp .= $arrVal[$j];
}else{
$temp .='->'.$arrVal[$j]."\n";
if($j == count($arrVal) - 1){
$temp .= "\n";
}else{
$temp .= substr($temp, 0, strpos($temp, "->"));
}
}
}
}
}
echo $temp;
As you iterate your array of arrow-delimited strings, explode each element on its arrows, separate the the first value from the rest, then iterate the remaining elements from the explosion and prepend the cached, first value and push into the result array.
Code: (Demo)
$result = [];
foreach ($arr as $string) {
$parts = explode('->', $string);
$parent = array_shift($parts);
foreach ($parts as $child) {
$result[] = "{$parent}->$child";
}
}
var_export($result);
Here the solution:
<?php
//This might help full
$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
'Users->User Departments->Department Hierarchy',
'Settings->Registrar->Finance',
'Logs->Second Opinion Log'];
$result="";
$newline="<br>";
foreach($arr as $data){
$wordlist=explode('->',$data);
$firstword=$wordlist[0];
$temp='';
foreach($wordlist as $key=>$value){
if($key > 0){
$temp.=$firstword."->".$value.$newline;
}
}
$temp.=$newline;
$result.=$temp;
}
echo $result;
?>
Output :
Governance->Policies
Governance->Prescriptions
Governance->CAS Alerts
Users->User Departments
Users->Department Hierarchy
Settings->Registrar
Settings->Finance
Logs->Second Opinion Log
$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
'Users->User Departments->Department Hierarchy',
'Settings->Registrar->Finance',
'Logs->Second Opinion Log'];
foreach ($arr as $path) {
$path_elements = explode('->', $path);
if (count($path_elements) > 1) {
$path_head = $path_elements[0];
$path_tail = array_slice($path_elements, 1);
foreach ($path_tail as $path_item) {
echo $path_head, '->', $path_item, "<br>";
}
echo "<br>";
}
}
Demo : https://onlinephp.io/c/9eb2d
Or, using JOIN()
$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
'Users->User Departments->Department Hierarchy',
'Settings->Registrar->Finance',
'Logs->Second Opinion Log'];
foreach ($arr as $path) {
$path_elements = explode('->', $path);
if (count($path_elements) > 1) {
$path_head = $path_elements[0];
$path_tail = array_slice($path_elements, 1);
echo
$path_head,
'->',
join('<br>'. $path_head.'->',$path_tail),
'<br><br>';
}
}
Demo : https://onlinephp.io/c/c1826

PHP Array output with comma and "or" [duplicate]

This question already has answers here:
Implode an array with ", " and add "and " before the last item
(16 answers)
Closed 7 years ago.
My php output is an array. Like:
$array = array('banana', 'mango', 'apple');
Now If output is only 'Banana' then it will show simply
Banana
If output is 'banana' & 'mango' or 'apple' the i want to show like
Banana or Mango
If output is all.. then result will be shown
Banana, Mango or Apple
Now I can show result with comma using this code
echo implode(",<br/>", $array);
But How to add or ??
Please help.
Try this:
<?php
$array = array('banana','mango','apple');
$result = '';
$maxelt = count($array) - 1;
foreach($array as $n => $item) {
$result .= ( // Delimiter
($n < 1) ? '' : // 1st?
(($n >= $maxelt) ? ' or ' : ', ') // last or otherwise?
) . $item; // Item
}
echo $result;
use the count and map with that like
$count = count($your_array);
if($count > 3){
end($array); // move the internal pointer to the end of the array
$key = key($array); // fetches the key of the element pointed to by the internal pointer
$last = $your_array[$key];
unset($your_array[$key]);
echo implode(",<br/>", $your_array)."or"$last;
}
you can replace last occurrence of a string in php by this function:
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if($pos !== false)
{
$subject = substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
$array = array('banana', 'mango', 'apple');
$output = implode(", ", $array);
echo $output = str_lreplace(',',' or',$output);
$count = count($array);
if( $count == 1 ) {
echo $array[0];
} else if ( $count == 2 ) {
echo implode(' or ', $array);
} else if ( $count > 2 ) {
$last_value = array_pop( $array );
echo implode(', ', $array).' or '.$last_value;
}
please try below Code :
$array = array('banana','mango','apple');
$string = null;
if(count($array) > 1){
$string = implode(',',$array);
$pos = strrpos($string, ',');
$string = substr_replace($string, ' or ', $pos, strlen(','));
}elseif(count($array) == 1){
$string = $array[0];
}
echo $string;

Comma separated string to parent child relationship array php

I have a comma separated string like
$str = "word1,word2,word3";
And i want to make a parent child relationship array from it.
Here is an example:
Try this simply making own function as
$str = "word1,word2,word3";
$res = [];
function makeNested($arr) {
if(count($arr)<2)
return $arr;
$key = array_shift($arr);
return array($key => makeNested($arr));
}
print_r(makeNested(explode(',', $str)));
Demo
function tooLazyToCode($string)
{
$structure = null;
foreach (array_reverse(explode(',', $string)) as $part) {
$structure = ($structure == null) ? $part : array($part => $structure);
}
return $structure;
}
Please check below code it will take half of the time of the above answers:
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
$result = array($arr[$i] => $result);
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';
Here is another code for you, it will give you result as you have asked :
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
if($i == 0){
$result = array($arr[$i] => $result);
}else{
$result = array(array($arr[$i] => $result));
}
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';

Multiple String Replace Based on Index

I need to replace multiple sections of a string based on their indices.
$string = '01234567890123456789';
$replacements = array(
array(3, 2, 'test'),
array(8, 2, 'haha')
);
$expected_result = '012test567haha0123456789';
Indices in $replacements are expected not to have overlaps.
I have been trying to write my own solution, split the original array into multiple pieces based on sections which needs to be replaced or not, and finally combine them:
echo str_replace_with_indices($string, $replacements);
// outputs the expected result '012test567haha0123456789'
function str_replace_with_indices ($string, $replacements) {
$string_chars = str_split($string);
$string_sections = array();
$replacing = false;
$section = 0;
foreach($string_chars as $char_idx => $char) {
if ($replacing != (($r_idx = replacing($replacements, $char_idx)) !== false)) {
$replacing = !$replacing;
$section++;
}
$string_sections[$section] = $string_sections[$section] ? $string_sections[$section] : array();
$string_sections[$section]['original'] .= $char;
if ($replacing) $string_sections[$section]['new'] = $replacements[$r_idx][2];
}
$string_result = '';
foreach($string_sections as $s) {
$string_result .= ($s['new']) ? $s['new'] : $s['original'];
}
return $string_result;
}
function replacing($replacements, $idx) {
foreach($replacements as $r_idx => $r) {
if ($idx >= $r[0] && $idx < $r[0]+$r[1]) {
return $r_idx;
}
}
return false;
}
Is there any more effective way to achieve the same result?
The above solution doesn't look elegant and feels quite long for string replacement.
Use this
$str = '01234567890123456789';
$rep = array(array(3,3,'test'), array(8,2,'haha'));
$index = 0;
$ctr = 0;
$index_strlen = 0;
foreach($rep as $s)
{
$index = $s[0]+$index_strlen;
$str = substr_replace($str, $s[2], $index, $s[1]);
$index_strlen += strlen($s[2]) - $s[1];
}
echo $str;

PHP combine arrays on similar elements

I have some data in this format:
even--heaped<br />
even--trees<br />
hardrocks-cocked<br />
pebble-temple<br />
heaped-feast<br />
trees-feast<br />
and I want to end up with an output so that all lines with the same words get added to each other with no repeats.
even--heaped--trees--feast<br />
hardrocks--cocked<br />
pebbles-temple<br />
i tried a loop going through both arrays but its not the exact result I want. for an array $thing:
Array ( [0] => even--heaped [1] => even--trees [2] => hardrocks--cocked [3] => pebbles--temple [4] => heaped--feast [5] => trees--feast )
for ($i=0;$i<count($thing);$i++){
for ($j=$i+1;$j<count($thing);$j++){
$first = explode("--",$thing[$i]);
$second = explode("--",$thing[$j]);
$merge = array_merge($first,$second);
$unique = array_unique($merge);
if (count($unique)==3){
$fix = implode("--",$unique);
$out[$i] = $thing[$i]."--".$thing[$j];
}
}
}
print_r($out);
but the result is:
Array ( [0] => even--heaped--heaped--feast [1] => even--trees--trees--feast [4] => heaped--feast--trees--feast )
which is not what i want. Any suggestions (sorry about the terrible variable names).
This might help you:
$in = array(
"even--heaped",
"even--trees",
"hardrocks--cocked",
"pebbles--temple",
"heaped--feast",
"trees--feast"
);
$clusters = array();
foreach( $in as $item ) {
$words = explode("--", $item);
// check if there exists a word in an existing cluster...
$check = false;
foreach($clusters as $k => $cluster) {
foreach($words as $word) {
if( in_array($word, $cluster) ) {
// add the words to this cluster
$clusters[$k] = array_unique( array_merge($cluster, $words) );
$check = true;
break;
}
}
}
if( !$check ) {
// create a new cluster
$clusters[] = $words;
}
}
// merge back
$out = array();
foreach( $clusters as $cluster ) {
$out[] = implode("--", $cluster);
}
pr($out);
Try this code:
<?php
$data = array ("1--2", "3--1", "4--5", "2--6");
$n = count($data);
$elements = array();
for ($i = 0; $i < $n; ++$i)
{
$split = explode("--", $data[$i]);
$word_num = NULL;
foreach($split as $word_key => $word)
{
foreach($elements as $key => $element)
{
if(isset($element[$word]))
{
$word_num = $key;
unset($split[$word_key]);
}
}
}
if(is_null($word_num))
{
$elements[] = array();
$word_num = count($elements) - 1;
}
foreach($split as $word_key => $word)
{
$elements[$word_num][$word] = 1;
}
}
//combine $elements into words
foreach($elements as $key => $value)
{
$words = array_keys($value);
$elements[$key] = implode("--", $words);
}
var_dump($elements);
It uses $elements as an array of hashes to store the individual unique words as keys. Then combines the keys to create appropriate words.
Prints this:
array(2) {
[0]=>
string(10) "1--2--3--6"
[1]=>
string(4) "4--5"
}
Here is a solution with a simple control flow.
<?php
$things = array('even--heaped', 'even--trees', 'hardrocks--cocked',
'pebble--temple', 'heaped--feast' ,'trees--feast');
foreach($things as $thing) {
$str = explode('--', $thing);
$first = $str[0];
$second = $str[1];
$i = '0';
while(true) {
if(!isset($a[$i])) {
$a[$i] = array();
array_push($a[$i], $first);
array_push($a[$i], $second);
break;
} else if(in_array($first, $a[$i]) && !in_array($second, $a[$i])) {
array_push($a[$i], $second);
break;
} else if(!in_array($first, $a[$i]) && in_array($second, $a[$i])) {
array_push($a[$i], $first);
break;
} else if(in_array($first, $a[$i]) && in_array($second, $a[$i])) {
break;
}
$i++;
}
}
print_r($a);
?>
It seems you have already selected user4035's answer as best.
But i feel this one is optimized(Please correct me if i am wrong): eval.in
Code:
$array = Array ( 'even--heaped' , 'even--trees' ,'hardrocks--cocked' , 'pebbles--temple' , 'heaped--feast' , 'trees--feast' );
print "Input: ";
print_r($array);
for($j=0;$j < count($array);$j++){
$len = count($array);
for($i=$j+1;$i < $len;$i++){
$tmp_array = explode("--", $array[$i]);
$pos1 = strpos($array[$j], $tmp_array[0]);
$pos2 = strpos($array[$j], $tmp_array[1]);
if (!($pos1 === false) && $pos2 === false){
$array[$j] = $array[$j] . '--'.$tmp_array[1];unset($array[$i]);
}elseif(!($pos2 === false) && $pos1 === false){
$array[$j] = $array[$j] . '--'.$tmp_array[0];unset($array[$i]);
}elseif(!($pos2 === false) && !($pos1 === false)){
unset($array[$i]);
}
}
$array = array_values($array);
}
print "\nOutput: ";
print_r($array);

Categories