How to perform an action on each imploded value? - php

I do not have a real use case but am simply wondering if this is possible and how i should do it.
Let's say I have the following array:
$array = array('1234', '5678', '9101', '1121', '3141');
And I would like to implode that.
$string = implode(',', $array);
Let's say I would like to perform an action on the values before they get implodes. For example reversing the string using strrev(). How would I go about this?
Edit
I will try to explain it a little better.
$array = range('a', 'z');
// I know this is not possible
$string = implode(', ', strtoupper($array));
// Desired output : A, B, C, D ...
I am wondering if it can be done using array_map() but ain't good in working with that function.

array_map function should work fine for built-in and "custom" functions(as a first argument of the function):
$array = array('1234', '5678', '9101', '1121', '3141');
$string = implode(', ', array_map("strrev", $array));
print_r($string); // "4321, 8765, 1019, 1211, 1413"
Another approach:
function addSeparator($word, $char = "-") {
$words = str_split($word, 2);
return implode($char, $words);
}
$string = implode(', ', array_map("addSeparator", $array));
print_r($string); // "12-34, 56-78, 91-01, 11-21, 31-41"

Simply do your logic before imploding:
$array = array('1234', '5678', '9101', '1121', '3141');
foreach ($array as &$value) {
$value = strrev($value);
}
$string = implode(',', $array);

Related

Replacing ',' characters in only odd positions

I need replace ',' characters with regex in php, but only in odd positions
I have:
{"phone","11975365654","name","John Doe","cpf","42076792864"}
I want replace ',' to ':', but only the odd:
{"phone":"11975365654","name":"John Doe","cpf":"42076792864"}
I'm trying this regex:
preg_replace('/,/', ':', $data)
But it get all quotes and no only the odd.
Can you help me?
Make it simple:
preg_replace('/(("[a-z]+"),(".+?"))+/', '$2:$3', $a)
Rather than regex, this just converts the list to an array (using str_getcsv() to cope with the quotes). Then loops every other item in the list, using that item as the key and the next item as the value. This can then be json_encoded() to give the result...
$data = str_getcsv(trim($input, "{}"));
$output = [];
for ( $i=0, $k=count($data); $i < $k; $i+=2) {
$output[$data[$i]] = $data[$i+1];
}
echo json_encode($output);
It is not ideal to use regex for this task. Having said that, if you know that your input can be matched by a simple regex, this should do it :
$str = '{"phone","11975365654","name","John Doe","cpf","42076792864"}';
$result = preg_replace('/,(.*?(?:,|[^,]*$))/ms', ':\\1', $str);
This lenient to some extra characters but it will fail if any string contains commas
Example
Here's an example of using standard PHP functions:
$input = '{"phone","11975365654","name","John Doe","cpf","42076792864"}';
$dataIn = str_getcsv(trim($input, '{}'));
$keys = array_filter($dataIn, function ($key) { return !($key & 1); }, ARRAY_FILTER_USE_KEY);
$values = array_filter($dataIn, function ($key) { return $key & 1; }, ARRAY_FILTER_USE_KEY);
$DataOut = array_combine($keys, $values);
$output = json_encode($DataOut);
echo $output;
This code is a lot longer than using a regex, but it is probably easier to read and maintain in the long run. It can cope with commas in the values.
Another option could be using array_splice and loop while there are still elements in the array:
$str = '{"phone","11975365654","name","John Doe","cpf","42076792864"}';
$data = str_getcsv(trim($str, '{}'));
$result = array();
while(count($data)) {
list($k, $v) = array_splice($data, 0, 2);
$result[$k] = $v;
}
echo json_encode($result);
Output
{"phone":"11975365654","name":"John Doe","cpf":"42076792864"}

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

Php first split then for loop

I have a string like this:
$d = 'game, story, animation, video';
And I want to change it to a result like this:
game, story, animation, video
So I think I have to split $d by ',' then use a for loop.
I have tried this:
$d = 'game, story, animation, video';
list($a, $b, $c, $d) = explode(" ,", $d);
But how do I split it if I don't know how many ',' are going to be there, and reach the desired result?
There are many ways this could be accomplished here is one.
by using a foreach loop you should be able to accomplish what you are attempting to do.
You also need to assign you array items correctly, by casting as a string and using the [ ] shorthand or using array()
$d = "game, story, animation, video";
$out = '' ;
foreach(explode(",",$d) as $item){
$out .= "<a href='$item' />$item</a>";
}
echo $out;
and if you need the , between you could use this
$d = "game, story, animation, video";
$out = [] ;
foreach(explode(",",$d) as $item){
$out []= "<a href='$item' />$item</a>";
}
echo implode(",",$out);
read more here
implode
explode
foreach
The key here is to realise that you can break this line into two parts:
list($a, $b, $c, $d) = explode(" ,", $d);
First, it takes the string $d and splits it into an array, let's call it $items:
$items = explode(" ,", $d);
Then the list() construct takes the items from that array and puts them into separate named variables:
list($a, $b, $c, $d) = $items;
If you don't know how many items are going to be in the list, you can just skip the second step, and work with the array, probably using a foreach loop:
foreach ( $items as $item ) {
echo "Doing something with '$item'...";
}
<?php
$in = 'game, story, animation, video';
$out = preg_replace('#([a-z]+)#', '$1', $in);
var_dump($out);
Or:
$tags = explode(',', $in);
$tags = array_map('trim', $tags);
$out = [];
foreach($tags as $tag)
$out[] = '' . $tag . '';
$out = implode(', ', $out);
var_dump($out);
Output for each:
string(112) "game, story, animation, video"

php replace all strings in array, and output comma seperated string

Wrote a little snippet that replaces all strings in an array, and finally outputs them as a comma separated string (shown below).
It seems a bit much though for such simple functionality. So my question is can anyone come up with a more elegant way of writing this?
$arr = array('first', 'second', 'third');
$size = count($arr);
$newArr = array();
for($i=0; $i<$size; $i++) {
$newArr[$i] = str_replace($arr[$i], '?', $arr[$i]);
}
$final = implode(', ', $newArr);
echo $final;
str_replace() accepts arrays:
$newArr = str_replace($arr, '?', $arr);
$final = implode(', ', $newArr);
But I hope this was just an example as you are just replacing anything in the array with ? which is easier done.
An other form to your snippet...
<?php
$arr = array('first', 'second', 'third');
foreach ($arr as $item) {
$na[] = str_replace($item, '?', $item);
}
echo implode(', ', $na);
Hope help you!

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