Convert array to string - php

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

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 split array in php with 2 strings?

How to split array with , in 2 parts so that that can be used as 2 strings in php?
I am getting this kind of array you can view image with this list.
I want to split this array to post id and title in separate columns.
<li id="recordsArray_'.$value['id'].','.$value['title'].'"></li>
Give a try with below code if it works for you
$arr = array('1,test1','2,test2','3,test3');
foreach($arr as $ar){
$res = explode(',', $ar);
$id = $res[0];
$title = $res[1];
echo 'id-'.$id;
echo ' title-'.$title;
echo '<br>';
}
If you want to separate array into two string, you can use explode like this short code:
$item = '4,test';
$var = explode(',', $item);
echo $var;
and for loop array, you can use
$array = array(YOUR_ARRAY);
foreach($array as $item){
$var = explode(',', $item);
echo $var;
}
Update 1:
You can use a simple array like below code:
$array = array(4, 'salar');
and use a code like this:
$array = array(4, 'salar');
foreach ($array as $item) {
dump(explode(',', $item));
}

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='';
};

how will i implode the result of array_diff

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);
?>

Replace string with values from multidimensional array based on a key

I have a variable with multiple number stored as a string:
$string = "1, 2, 3, 5";
and multidimensional array with other stored values:
$ar[1] = array('title#1', 'filename#1');
$ar[2] = array('title#2', 'filename#2');
$ar[3] = array('title#3', 'filename#3');
$ar[4] = array('title#4', 'filename#4');
$ar[5] = array('title#5', 'filename#5');
My goal is to replace number from $string with related tiles from $ar array based on associated array key. For an example above I should to get:
$string = "title#1, title#2, title#3, title#5";
I have tried to loop through $ar and do str_replace on $string, but final value of $string is always latest title from related array.
foreach($ar as $key => $arr){
$newString = str_replace($string,$key,$arr[0]);
}
Any tips how to get this solved?
Thanks
you can do it by str_replace by concat each time or you can do it by explode and concat.
Try Like this:
$string = "1, 2, 3, 5";
$arrFromString = explode(',', $string);
$newString = '';
foreach($ar as $intKey => $arr){
foreach($arrFromString as $intNumber){
if($intKey == $intNumber) {
$newString .= $arr[0].',';
}
}
}
$newString = rtrim($newString,',');
echo $newString;
Output:
title#1,title#2,title#3,title#5
live demo
You can use explode() and implode() functions to get the numbers in $string as an array and to combine the titles into a string respectively:
$res = array();
foreach (explode(", ", $string) as $index) {
array_push($res, $ar[$index][0]);
}
$string = implode(", ", $res);
print_r($string);
will give you
title#1, title#2, title#3, title#5;

Categories