how will i implode the result of array_diff - php

How will i separated by comma the result of array_diff i tried this code but it gave me Warning: explode() expects parameter 2 to be string, array give
Warning: Invalid argument supplied for foreach()
<?php
$row['IMEI_MX'] = '123,222,333';
$row2["IMEI_MX"] = '123,222';
$imei = $row["IMEI_MX"];
$imeiserial = explode(',', $imei);
$imeitransfer = $row2["IMEI_MX"];
$imeitransferserial = explode(',', $imeitransfer);
$a1 = $imeiserial;
$a2 = $imeitransferserial;
$result = array_diff($a1,$a2);
$separate = implode(' ', $result);
foreach($separate as $is){
echo $is;
}

I think you just want to show the values of first string which are not in second string .
Tried this one
<?php
$row['IMEI_MX'] = '123,222,333,444';
$row2["IMEI_MX"] = '123,222';
$imei = $row["IMEI_MX"];
$imeiserial = explode(',', $imei);
$imeitransfer = $row2["IMEI_MX"];
$imeitransferserial = explode(',', $imeitransfer);
$a1 = $imeiserial;
$a2 = $imeitransferserial;
$result = array_diff($a1,$a2);
$sting = implode(',',$result);
echo $sting;
?>
It will result as
333,444

Use implode, it is the opposite function, you are using.

Use implode to get comma separated array values
$separate = implode(',', $result);

Explode is used for converting a string into array, while specifying the delimiter. Implode is the opposite one - you specify the glue for converting an array to string.
In your case, you don't need an explode after array_diff, because the result is itself an array. There's no need to convert anything. So, you just need to remove that line before the foreach:
foreach($result as $is){
echo $is;
}
When you use implode in the foreach, it throughs an error, because you're trying to loop through a string (the result of the implode operation) and the foreach operation expects an array.
UPDATE:
Follow the above code if you want to echo all items of the resulting array. If you want to display the array as a string, separated by comma, you need to go with implode but dismis the foreach after.
$separate = implode(',', $result);
echo $separate;

try this no need foreach just use implode
<?php
$row['IMEI_MX'] = '123,222,333,444';
$row2["IMEI_MX"] = '123,222';
$imei = $row["IMEI_MX"];
$imeiserial = explode(',', $imei);
$imeitransfer = $row2["IMEI_MX"];
$imeitransferserial = explode(',', $imeitransfer);
$a1 = $imeiserial;
$a2 = $imeitransferserial;
$result = array_diff($a1,$a2);
echo implode(',',$result);
?>

Related

Pass comma separated key string and get value of array according to key in PHP

I am trying to get value from array and pass only comma separated key string and get same output without. Is it possible without using foreach statement. Please suggest me.
<?php
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
$keyarray = explode(",",$str);
$valArr = array();
foreach($keyarray as $key){
$valArr[] = $array[$key];
}
echo $valStr = implode(",", $valArr);
?>
Output : apple,banana,orange
Use array_intersect_key
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
$keyarray = explode(",",$str);
echo implode(",", array_intersect_key($array, array_flip($keyarray)));
https://3v4l.org/gmcON
One liner:
echo implode(",", array_intersect_key($array, array_flip(explode(",",$str))));
A mess to read but a comment above can explain what it does.
It means you don't need the $keyarray
Suggestion : Use separate row for each value, to better operation. Although you have created right code to get from Comma sparate key to Value from array, but If you need it without any loop, PHP has some inbuilt functions like array_insersect , array_flip to same output
$str = "1,2";
$arr1 = ["1"=>"test1","2"=>"test2","3"=>"test3"];
$arr2 = explode(",",$str);
echo implode(", ",array_flip(array_intersect(array_flip($arr1),$arr2)));
Live demo
you can try using array_filter:
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
$keyarray = explode(",",$str);
$filtered = array_filter($array, function($v,$k) use($keyarray){
return in_array($k, $keyarray);
},ARRAY_FILTER_USE_BOTH);
print_r($filtered);
OUTPUT
Array
(
[1] => apple
[2] => banana
[3] => orange
)
Another way could be using array_map():
echo $valStr = implode(",", array_map(function ($i) use ($array) { return $array[$i]; }, explode(",", $str)));
Read it from bottom to top:
echo $valStr = implode( // 3. glue values
",",
array_map( // 2. replace integers by fruits
function ($i) use ($array) {
return $array[$i];
},
explode(",", $str) // 1. Split values
)
);

How to apply double quotes to each value in a comma-space delimited string?

I want to add double quotes of my every array.
Original value is:
192.168.183.2, 192.168.183.28
The current result is:
"192.168.183.2, 192.168.183.28"
What I want is:
"192.168.183.2", "192.168.183.28"
and here is my code:
$allowedIP = array($dScheduler['ALLOWED_IP_ADDRESS']);
echo $newarray='"'.implode('","', $allowedIP).'"';
Your input value is a string, so handle it with just one string function call (str_replace()):
Code: (Demo)
$dScheduler['ALLOWED_IP_ADDRESS']='192.168.183.2, 192.168.183.28'; // your input string
$wrapped='"'.str_replace(', ','", "',$dScheduler['ALLOWED_IP_ADDRESS']).'"';
echo $wrapped;
echo "\n\n";
// if you want an array:
$array=explode(', ',$wrapped); // generate result array
foreach($array as $v){
echo "$v\n";
}
The value delimiter in your input string is: ,, so you just need to change it to ", " and wrap the entire string in " as well.
Then you simply explode on the commas to generate your desired array of elements.
Output:
"192.168.183.2", "192.168.183.28"
"192.168.183.2"
"192.168.183.28"
Do it through a loop:
$new_array = array();
foreach($array as $a) {
$new_array[] = '"'.$a.'"';
}
It will create a new array with ", around each element.
You can use array_map
<?php
$allowedIP = array('192.168.183.2, 192.168.183.28');
$arrAllowedIP = explode(',', $allowedIP[0]);
$quotedIP = array_map(function($val)
{
return '"'.trim($val).'"';
}, $arrAllowedIP);
Try This,
$arr = ["192.168.183.2", "192.168.183.28"];
$imp = '"'.implode('", "', $arr).'"'; // to string with double quote
$exp = explode(',', $imp); // to array with double quote
echo $im;
print_r($exp);
$allowedIP = array('192.168.183.2, 192.168.183.28');
$new= implode($allowedIP);
$fl=',';
foreach (explode(',',$new) as $v){
echo '"'.$v.'"'.$fl;
$fl='';
};

clean string removing a list of values

i was writing this code to remove a list of values from a dynamic string key
//key
$chiave = "motore a scoppio di seconda generazione";
//sanitize string
//$chiave = pulisci($chiave);
//clean from double whitespaces
$chiave = preg_replace('/\s+/', ' ',$chiave);
//convert in lowercase
$chiave = strtolower($chiave);
//define array with all values to remove
$togliere = array("a","il","lo","la","egli","gli","li","di","do","e","è","alla","alle","&","un","uno","una");
$togliere2 = array("d'","l'");
//explode words
$keyval = explode(" ",$chiave);
//remove values
$keyvalclean = array_values(array_diff($keyval, $togliere));
//remove others values
$valori = array();
for($x=0; $x<=count($keyvalclean); $x++){
$valori[] = str_replace($togliere2,"",$keyvalclean[$x]);
}
//print the result
echo implode(" ",$valori);
this will output "motore scoppio seconda generazione"
there is a faster and optimized code to do that?
thanks
Your code looks okay to me. But you don't need to loop through the array to remove the values using str_replace(). This function can take an array as its argument and perform the replacement on each one of them in one go.
This:
$valori = array();
for($x=0; $x<=count($keyvalclean); $x++){
$valori[] = str_replace($togliere2,"",$keyvalclean[$x]);
}
can be changed to just:
$valori = str_replace($togliere2, "", $keyvalclean);
echo implode(" ",$valori);
Demo
Use str_replace()
You could insert an array to replaced by "" with this function.

Combine Arrays and update a string with values

I have two issues I was hoping to get help on:
Combine two arrays into one string
and add some formatting
insert the new string into a
specific spot in a bigger string.
I have two arrays:
$array_1 = array("100","200","300");
$array_2 = array("abc","def","ghi");
$result = array_merge($array_1, $array_2);
foreach ($result as $val){
//NEED HELP HERE create a string that adds a "mac=" to the beginning of the current $val and adds a "/n" to the end of the current value.
}
The above should somehow create the string below:
$my_string = "mac=100/n
mac=200/n
mac=300/n
mac=abc/n
mac=def/n
mac=ghi/n";
Now for Part #2
I have a current string that was created already:
$current_String = "[MACS]/n
mac=blah1/n
mac=blah2/n
mac=blah3/n
[SERVICES]";
My last issue is to replace everything between [MACS]/n and [SERVICES] with $my_string
So I should end up with:
$updated_String = "[MACS]/n
mac=100/n
mac=200/n
mac=300/n
mac=abc/n
mac=def/n
mac=ghi/n
[SERVICES]";
Any help or insight would be greatly appreciated.
This should work:
$array_1 = array("100","200","300");
$array_2 = array("abc","def","ghi");
$result = array_merge($array_1, $array_2);
$myString = "[MACS]/n\nmac=" . implode($result, "/n\nmac=") . "/n\n[SERVICES]";
//replace in other string
$macsIndex = strrpos($currentString, "[MACS]");
$servicesIndex = strrpos($currentString, "[SERVICES]");
$currentString = substr($currentString, 0, $macsIndex) . $myString . substr($currentString, servicesIndex+10);
Outputs:
[MACS]/n
mac=100/n
mac=200/n
mac=300/n
mac=abc/n
mac=def/n
mac=ghi/n
[SERVICES]
$formatted = '';
foreach ($result as $val){
$val = sprintf("mac=%s\n", $val);
$formatted .= $val;
}

Convert array to string

I have an array of strings and I need to build a string of values separated by some
character like comma
$tags;
implode()
There is a simple function called implode.
$string = implode(';', $array);
You should use the implode function.
For example, implode(' ',$tags); will place a space between each item in the array.
If any one do not want to use implode so you can also use following function:
function my_implode($separator,$array){
$temp = '';
foreach($array as $key=>$item){
$temp .= $item;
if($key != sizeof($array)-1){
$temp .= $separator ;
}
}//end of the foreach loop
return $temp;
}//end of the function
$array = array("One", "Two", "Three","Four");
$str = my_implode('-',$array);
echo $str;
There is also an function join which is an alias of implode.
Using implode
$array_items = ['one','two','three','four'];
$string_from_array = implode(',', $array_items);
echo $string_from_array;
//output: one,two,three,four
Using join (alias of implode)
$array_items = ['one','two','three','four'];
$string_from_array = join(',', $array_items);
echo $string_from_array;
//output: one,two,three,four

Categories