Prepared String Before Comma - php

I've got an array;
Array
(
[0] => Test1
[1] => Test2
[2] => Test3
)
Now I've used the Implode Function from which i got the comma separated String:
Test1, Test2, Test3
now I'd like to put a quotes ("") before and after every word e.g.
"Test1", "Test2", "Test3"
How could I change it to work how I want.

Try this simple one-liner:
$quotedStrings = '"' . implode('","', $myArray) . '"';
The "glue" parameter may be a complex string, though you only have to put the " at the beginning and end.

While the answer from Axel is totally fine for the given szenario,
using array_map along with implode will also work.
And this has the advantage, that modifications to each element are not limited to the start/end of the element. For instance, you can turn each entry to lower-case as well, or perform other, more complex operations, before applying implode.
$quotedString = implode(",", array_map("myCallback", $myArray));
function myCallback($entry){
//here you can to whatever you like to EACH element.
return '"'.$entry.'"';
}
Consider this an option

You can use make a new array by using foreach loop and then use implode. Use the code below
<?php
$array = array("Test1","Test2","Test3");
$quotes = array();
foreach($array as $p){
$quotes[] = '"'.$p.'"';
}
echo implode(",",$quotes); // Outputs "Test1","Test2","Test3"
?>
Another way you can do it by enclosing the implode in "" quotes and then implode comma , in quotes.
<?php
$array = array("Test1","Test2","Test3");
echo '"'.implode('","',$array).'"'; // Outputs "Test1","Test2","Test3"
?>
Hope this helps you

Related

How to add string if two arrays are in php?

I have array values if there are two values i need to add a string "AND" if single value "AND" string should not be added. i have tried with the following code. cant get the required output
$unserialize_meta = array(0=>"Alcor",1=>"President",2=>"Treasurer");
$checks = array();
foreach($unserialize_meta as $meta){
$checks[]= $meta;
}
echo implode(" And ",$checks);
Output:
Alcor And President
Alcor And President And
required output:
Alcor And President
Alcor And President
You can use the implode function for this. Details can be found here.
Considering the above code:
$unserialize_meta = array(0=>"Alcor",1=>"President",2=>"Treasurer");
$checks = implode(" AND ", array_filter($unserialize_meta));
var_dump($checks);
The array_filter will remove any empty values in the array.
I thing you don't need to loop array. you just need to implode array with the string. Please try below code it will add string AND with your array values.
$unserialize_meta = array(0=>"Alcor",1=>"President",2=>"Treasurer");
if(!empty($unserialize_meta )) {
echo implode(" And ",$unserialize_meta);
}
Output:
Alcor And President And Treasurer
There is mistake saved in array values in array I'm getting empty array. So I add a empty array check :
if(!empty($meta)){
$checks[]= $meta;
}

Array Split In PHP

Now my array is Storing values like
Array([0] => "Aaa", "bbb", "ccc")
How can I make this Array as below using PHP
Array[0] = "Aaa", Array[1] = "bbb"
How to make like this. I tried with explode its not taking values correctly If anyone knows solution. Please help me to get out of this. Thanks in advance.
$oldarray[0]='"abc","def","hij"';
$oldarray[1]='"abc","def","hij"';
$newarray=array();
foreach ($oldarray as $value) {
$newarray[] = str_replace('"','',explode(',',$value));
//print_r($value);die();
}
print_r($newarray);
Use explode
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter comma.
$array1 = explode(',',$array[0]);
Use str_replace to remove double quotes
str_replace('"', '', $array[0]);
$array1 = explode(',',str_replace('"', '',$array[0]));
Check array1[0], array1[1] and array1[2] to find your values
Use explode to split the value in multiple values based on the coma, use str_replace to remove the quotes :
you do something like this
$newarray = explode(',',str_replace('"', "",$oldarray[]));
or:
$newarray = explode('","',trim($oldarray[],'"'));
docs

To look for a simple way to extract matched parts of strings from an array

I want to extract matched parts of strings --digital part from an array
array("HK00003.Day","HK00005.Day").
<?php
$arr=array("HK00003.Day","HK00005.Day");
$result= array();
foreach ($arr as $item){
preg_match('/[0-9]+/',$item,$match);
array_push($result,$match[0]);
}
It can get the result :00003 00005,it seems tedious,preg_grep seems simple but the result is not what i want .
preg_grep('/[0-9]+/',$arr);
The output is "HK00003.Day","HK00005.Day", not 00003 00005,
is there more simple way to get the job done?
You can use preg_filter (which already uses preg_replace and does not require additional callback functions) to replace the each entry in the array with the number inside:
<?php
$arr = array("HK00003.Day","HK00005.Day");
$matches = preg_filter('/^.*?([0-9]+).*/', '$1',$arr);
print_r($matches);
?>
Output of a sample program:
Array
(
[0] => 00003
[1] => 00005
)
This should work for you:
(Here I just get rid off every character in your array which isn't a number with preg_replace())
<?php
$arr = ["HK00003.Day", "HK00005.Day"];
$result = preg_replace("/[^0-9]/", "", $arr);
print_r($result);
?>
output:
Array ( [0] => 00003 [1] => 00005 )
Your code is fine, not tedious at all. If you want a one-liner you can try something like this (remove everything that's not a digit):
array_push($result, preg_replace("~[^0-9]~", "", $item));
preg_grep return array entries that match the pattern! Therefore, it returns an array of entry rather than the matching string
try below:
preg_match_all('/[0-9]+/',implode('-',$arr),$result);

Quoting items when using implode function

I am trying to use the implode function on array; and its working fine and i am returning result fine as it should suppose to do. I would now like to add extra quotation marks at the start and end of each item.
EG: I am currently getting this result in implode:
jan,feb,march,april,etc,etc
Instead I would like each item to be quoted:
"jan","feb","march","april","etc","etc"
Here is little code how i am using to implode something from my array
$selectedMonths = implode(",",array_column($selectedMonths,'id'));
As it is already string, I tried this below code also, but it was of no use. as it is already a string, but when imploding the commas are not added.
foreach($selectedMonths as $value){
array_replace($selectedMonths,array_map('strval', array_slice($value, 0)));
}
Initially I am getting $selectedMonths as a json array, for which i have used json_decode() in php and in that foreach I have tried after converting the json array to associated array. But now how to add extra "" around every comma separated value?
This should work for you:
<?php
$array = array("jan", "feb", "march", "april", "etc", "etc");
echo '"' . implode('","', $array) . '"';
?>
Output:
"jan","feb","march","april","etc","etc"
It sounds like what you want to do, is get a JSON string from your array? For that you can use json_encode:
$json = json_encode($array);
But to append and prepend a quote mark to every string in an array, you can use array_map:
$array = ["jan","feb","march","april","etc","etc"];
$mapped = array_map($array, function($value) {
return '"' . $value . '"';
});

Trim unwanted characters from the end of the last element in an array

How do I modify the last element in an array?
The array looks like this:
$fields = array("firstName = 'Bob', ",
"lastName = 'Smith', ",
"email = 'bob#example.com', ",
"address = '123 anystreet', ");
The array is generated by a script which creates the values and adds the comma/space at the end of each string. I want to remove that comma/space from only the last element in that array. Keep in mind that the values could in fact contain a comma/space combination so only the last element and the last two characters of the last element need to be removed.
I've looked at the end() function but I don't think that is going to help since it just gets the value.
Edit Ok so I created this function/array so that I would only have one mysql function to update users. Sort of like a detect changes function and it only passes back the required/changed fields. I didn't realize there were problems associated with this approach. I thought that since I already had the mysql queries written in my old functions there shouldn't be an issue with this way. The file that it's in will not be accessible to the public. I'm going to use the best answer that works for me but I'm going to search for why this is problematic and I would appreciate comments/links as to what is wrong with this approach.
Like this!
end($array);
$key = key($array);
reset($array);
There's a shorthand way to do this, but it's easier to follow if it's broken out into pieces:
$index = count( $fields ) - 1;
$value = $fields[$index];
$fields[$index] = preg_replace( "/,\ $/", "", $value );
To change the value of the last numeric element:
$lastValue = array_pop($fields);
$fields[] = rtrim(', ',$lastValue);
If you are preparing these values for a query I would suggest storing everything without commas in an array then calling implode on that array when needed to prevent trailing comma problems
Array pop and push are the easiest way to do it for basic arrays. (I know that isn't technically the question but many people will come here looking for the answer in relation to simple arrays as well).
<?php
function update_last(&$array, $value){
array_pop($array);
array_push($array, $value);
}
?>
Then you can use the function like this:
<?php
$array = [1,2,3];
update_last($array, 4); //$array = [1,2,4];
?>
There are few ways:
1) For associative arrays, if you don't know the last element key, you better find the last element key first and change its value.
$array[end((array_keys($array)))] .= ' additional text';
2) if you don't know and don't care about keys, you can cut the last element and create a new one.
$array[] = array_pop($array).' additional text';
The last element of an array can always be retrieved using array_pop(), no matter how the array is indexed. It will also remove that element from the array, which is very useful if we want to modify and then add it again, as you cannot modify the element in-place.
What you are trying to do can be done with a simple, single line of code:
$fields[] = preg_replace("/, $/", "", array_pop($fields));
That's it. Here's what it does:
preg_replace() searches for a Regex pattern in a string and if found, replaces the match with an alternative string.
The pattern we search for is /, $/, which means: Match for ", " (comma + space) but only if it is at the very end of the string ($).
The replacement string is simply an empty string (""), thus the match is just deleted from the string.
The string we want to perform that replacement on is array_pop($fields), the last element of the array $fields, which is also removed from that array.
The modified string is then re-added to the array at the end ($fields[] = adds an element to an array without an explicit key and makes it the new last element).
Let's test it:
$fields = array(
"firstName = 'Bob', ",
"lastName = 'Smith', ",
"email = 'bob#example.com', ",
"address = '123 anystreet', ");
print "Before:\n\n";
print_r($fields);
$fields[] = preg_replace("/, $/", "", array_pop($fields));
print "\nAfter:\n\n";
print_r($fields);
Output:
Before:
Array
(
[0] => firstName = 'Bob',
[1] => lastName = 'Smith',
[2] => email = 'bob#example.com',
[3] => address = '123 anystreet',
)
After:
Array
(
[0] => firstName = 'Bob',
[1] => lastName = 'Smith',
[2] => email = 'bob#example.com',
[3] => address = '123 anystreet'
)
Note how the last comma is gone? Just try it yourself.
stumbled upon this today. i think the easiest non-pointer-breaking way would be:
array_splice($array, -1, 1, strtolower(end(array_values($array))).'blah' );
of course you can drop array_values if you dont have to care for the pointer.
but i wonder if this is a good way, since the extract-n-replace-stuff of splice could be more demanding than a pop or sth?
PHP 7 >= 7.3.0
$array[array_key_last($array)] = 'new value';
Demo
$fields = array(
"firstName = 'Bob', ",
"lastName = 'Smith', ",
"email = 'bob#example.com', ",
"address = '123 anystreet', "
);
$last = $fields[array_key_last($fields)];
$last = preg_replace( "/, $/", "", $last);
$fields[array_key_last($fields)] = $last;
I think PHP's Implode function might be a good alternative, instead of generating the commas yourself.
Barring that, you would have to use something like:
$lastfield = $fields[count($fields)-1];
$lastfield = str_split($lastfield,strlen($lastfield)-2);
$fields[count($fields)-1] = $lastfield;
The first and third lines are included to make the second line easier to read, but this could easily be compounded to one line.

Categories