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

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!

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"

How to perform an action on each imploded value?

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

php exploded associative array problem

I have php script as below;
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
$array = explode(",", $ages2);
echo $array["Peter"];
echo $ages["Peter"];
In this case, echo $ages["Peter"]; is working well, but echo $array["Peter"]; is not working. Can anybody solve this please..
Thanks in advance.
blasteralfred
You'll have to go in two steps :
First, explode using ', ', as a separator ; to get pieces of data such as "Peter"=>32
And, then, for each value, explode using '=>' as a separator, to split the name and the age
Removing the double-quotes arround the name, of course.
For example, you could use something like this :
$result = array();
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
foreach (explode(', ', $ages2) as $couple) {
list ($name, $age) = explode('=>', $couple);
$name = trim($name, '"');
$result[$name] = $age;
}
var_dump($result);
And, dumping the array, you'd get the following output :
array
'Peter' => string '32' (length=2)
'Quagmire' => string '30' (length=2)
'Joe' => string '34' (length=2)
Which means that using this :
echo $result['Peter'];
Would get you :
32
Of course it doesn't work. explode just splits by the given delimiter but doesn't create an associative array.
Your only hope if you really have such a string is to parse it manually. Either using preg_match_all, or I suppose you could do:
$array = eval('return array('.$ages2.');');
But of course this isn't recommended since it could go wrong in many many ways.
In any case I'm pretty sure you can refactor this code or give us more context if you need more help.
You'll need to build the array yourself by extracting the name and age:
<?php
$array = array();
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
foreach (explode(",", $ages2) as $element) {
$parts = explode("=>", $element);
if (count($parts) == 2) {
$name = str_replace(array('"', ' '), '', $parts[0]);
$age = (int) $parts[1];
$array[$name] = $age;
}
}
print_r($array);
$ages2 is not an array, so what you're trying here won't work directly, but you can transform a string with that structure into an array like this:
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
$items = explode(",", $ages2);
foreach ($items as $item) {
list($key,$value) = explode('=>',$item);
$key = str_replace('"','',trim($key)); // Remove quotes and trim whitespace.
$array[$key] = (int)$value;
}
If you var_dump($array), you'll have:
array(3) {
["Peter"]=>
int(32)
["Quagmire"]=>
int(30)
["Joe"]=>
int(34)
}
So you can do this as expected and get 32 back out:
echo $array['Peter']

Categories