comma separated if value in array is empty - php

I am stuck with a problem, I have fetched some values from a MySQL query and put them in to an array like so:
$add1 = $location->address1;
$add2 = $location->address2;
$twn = $location->town;
$pcode = $location->postcode;
$latitude = $location->lat;
$longitude = $location->lng;
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = rtrim(implode(',', $fullAddress), ',');
echo $string;
so that I can echo out a users address. The problem I am getting is that even if one of these values does not exist (and some don't because they are not all required fields), the comma is still echoed to the screen like:
add1,, town, br2 5lp
because there is an empty value in the database.
What I want to achieve is something like:
add1, town, br2 5lp
if the second part of the address is missing.
Can anyone help me figure this out?

try this.
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = implode(',', array_filter($fullAddress, 'strlen'));
echo $string;

The problem I am getting is that even if one of these values does not
exist (and some dont because they are not all required fields),
the comma is still echoed to the screen
That is what the implode function in php is supposed to do. If you want a different behavior, you will have to either change the way you create your CSV string or do some extra processing on the information you obtain from the implode function.
So use a for loop or a foreach loop to go through the address array. A for loop is faster than a foreach loop.
Using Foreach:
$add1 = $location->address1;
$add2 = $location->address2;
$twn = $location->town;
$pcode = $location->postcode;
$latitude = $location->lat;
$longitude = $location->lng;
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = "";
foreach($fullAddress as $value)
{
if(!empty($value))
$string .= $value.", ";
}
$string = rtrim($string, ", ");
echo $string;
You can do some extra processing on the created csv string of your own solution by maybe doing a str_replace() of all occurances of ,, with ,. This could be dangerous because if any of the values in your $fullAddress array contain a ,, as a valid string then that will also be replaced too with ,.

What you need is to assure array $fullAddress have no empty value, so php built-in function array_filter make this purpose very easy.
Just change your last codes to:
$string = implode(',', array_filter($fullAddress));
echo $string;
If the second parameter of array_filter is not supplied, all entries of array equal to FALSE will be removed. So just simply use array_filter($fullAddress) it make the code more clear and simple.

Related

Matching a string to another string with PHP

Im trying to filter some entry's in a While loop. This i'm trying to do with the strpos function, unfortunately when i use a variable as needle, i do not get an result.
No result:
$tra = strpos($HRreq, $entry_type)
result: $tra = strpos($HRreq, "string");
But, i need it to be variable in the while loop.
$select_exec = odbc_exec($amos_db,$select_personnel);
while ($row = odbc_fetch_array($select_exec)){
$username = $row['user_sign'];
$entry_type = $row['entry_type'];
$fullname1 = $row['lastname'] . $row['firstname'];
$fullname = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($fullname1))))));
$userno = $row['employee_no_i'];
$tra = strpos($HRreq, "$entry_type");
echo $entry_type ." = ". $tra;
}
I've added part of the code since the code is more than 500 lines long. I hope this is enough to get an idea of what i'm trying to accomplish
I discovered that the database returned with white spaces after the variable. I added a trim() and the problem was solved. It was a silly mistake.

PHP Convert a string of comma separated values into another format without using a loop

In php, if I had a string of comma separated data like this which came from a database:
John,Paul,Ringo,George
how could I convert it to something like this, without using a for loop or any extra processing. Does php have a function that can do this?
$str = 'John','Paul','Ringo','George';
I currently split the string using explode and then reformat it. Anyway to achieve this without doing that?
The formatted string is sent to a SQL where it's used in a MySQL IN() function.
If you absolutely don't want to use explode() you could use
$str = 'John,Paul,Ringo,George';
$newStr = "'" . str_replace(",","','", $str) . "'";
You can use preg_replace with $1 thing.
UPDATED:
See usage example:
echo preg_replace('((\\w+)(,?))', '"$1"$2', 'John,Paul,Ringo,George');
you can use explode like below
$db_data = 'John,Paul,Ringo,George';//from your db
$l = explode(',',$db_data);
echo "select * from table where column IN('".implode("','",$l)."')";
output:
select * from table where column IN('John','Paul','Ringo','George')
You can use the explode and implode functions in PHP.
$names = explode(',', 'John,Paul,Ringo,George');
echo implode(',', $names);
I hope I got you right:
$str_1 = 'John,Paul,Ringo,George';
$str_2 = explode(',', $str_1);
$str_3 = implode('\',\'', $str_2);
$str_4 = '\''.$str_3.'\'';
echo $str_4;
Output: 'John','Paul','Ringo','George'
$l = 'John,Paul,Ringo,George';
$lx = "'" . implode("','", explode(",", $l)) . "'";
echo $lx; // 'John','Paul','Ringo','George'

In comma delimited string is it possible to say "exists" in php

In a comma delimited string, in php, as such: "1,2,3,4,4,4,5" is it possible to say:
if(!/*4 is in string bla*/){
// add it via the .=
}else{
// do something
}
In arrays you can do in_array(); but this isn't a set of arrays and I don't want to have to convert it to an array ....
Try exploding it into an array before searching:
$str = "1,2,3,4,4,4,5";
$exploded = explode(",", $str);
if(in_array($number, $exploded)){
echo 'In array!';
}
You can also replace numbers and modify the array before "sticking it back together" with implode:
$strAgain = implode(",", $exploded);
You could do this with regex:
$re = '/(^|,)' + preg_quote($your_number) + '(,|$)/';
if(preg_match($re, $your_string)) {
// ...
}
But that's not exactly the clearest of code; someone else (or even yourself, months later) who had to maintain the code would probably not appreciate having something that's hard to follow. Having it actually be an array would be clearer and more maintainable:
$values = explode(',', $your_string);
if(in_array((str)$number, $values)) {
// ...
}
If you need to turn the array into a string again, you can always use implode():
$new_string = implode(',', $values);

Add quotation marks to comma delimited string in PHP

I have a form which is a select multiple input which POSTs values like this: option1,option2,option3 etc..
How is the best way to convert this to 'option1','option2','option3' etc...
Currenty I'm doing this, but it feels wrong??
$variable=explode(",", $variable);
$variable=implode("','", $variable);
The reason why I'm doing this is because I want to use the form select multiple inputs in a SQL Query using IN.
SELECT * FROM TABLE WHERE some_column IN ('$variable')
You can wrap whatever code in a function to make the "feels wrong" feeling disapear. E.g.:
function buildSqlInClauseFromCsv($csv)
{
return "in ('" . str_replace(",", "','", $csv) . "') ";
}
If $variable = "option1,option2,option3"
you can use:
"SELECT * FROM TABLE WHERE FIND_IN_SET(some_column, '$variable')"
Here is what I used:
WHERE column IN ('".str_replace(",", "','", $_GET[stringlist])."')
we know that implode converts array to string,we need to provide the separator and then array as shown below, here we have (coma ,) as a separator.
Implode breaks each element of an array with the given separator,I have conceited '(single quotes) with the separator.
$arr = array();
$arr[] = "raam";
$arr[] = "laxman";
$arr[] = "Bharat";
$arr[] = "Arjun";
$arr[] = "Dhavel";
var_dump($arr);
$str = "'".implode("','", $arr)."'";
echo $str;
output: 'raam','laxman','Bharat','Arjun','Dhavel'
There is only one correct way to escape strings for SQL - use the function provided by the database api to escape strings for SQL. While mysyl_* provides mysql_real_escape_string():
$choices = explode(",", $variable);
foreach($choices as &$choice)
$choice = "'".mysql_real_escape_string($choice)."'";
$choices = implode(",", $choices);
PDO provides a method that will add quotes at the same time:
$choices = explode(",", $variable);
foreach($choices as &$choice)
$choice = $pdoDb->quote($choice);
$choices = implode(",", $choices);
Note that PDO::prepare doesn't really work here

How to remove last comma (,) from array?

I've gone through this address:
Passing an array to a query using a WHERE clause
and found that if I use a join clause to separate values , is also at the end of the array. How can I remove last?
I am using like this
$ttst=array();
$ttst=array();
$tt = "SELECT frd_id FROM network WHERE mem_id='$userId'";
$appLdone = execute_query($tt, true, "select");
foreach($appLdone as $kk=>$applist){
$ttst[] = $applist['frd_id'];
}
$result = implode(',', $ttst);
then also coming last ,
Thanks.
but it doesn't give single quote to each value .
join(',', array_filter($galleries))
array_filter gets rid of empty elements that you seem to have. Of course, you should take care not to have empty elements in there in the first place.
You could use trim() (or rtrim()):
$myStr = 'planes,trains,automobiles,';
$myStr = trim($myStr, ',');
$str = "orange,banana,apple,";
$str = rtrim($str,',');
This will result in
$str = "orange,banana,apple";
Update
Based on your situation:
$result = implode(',', $ttst);
$result = rtrim($result,',');
$arr = array(...);
$last = end($arr);
unset($last);
If the trailing "," is an array element of itself, use array_pop(), else, use rtrim()
$array = array('one','two',3,',');
array_pop($array);
print_r($array);
Gives:
Array ( [0] => one 1 => two 2 => 3
)
No need for length. Just take from beginning to the (last character - 1)
$finalResult = $str = substr($result, 0, -1);
Use implode() instead! See Example #1 here http://php.net/manual/en/function.implode.php
Edit:
I think a quick fix would be (broken down in steps):
$temp = rtrim(implode(',', $ttst), ','); //trim last comma caused by last empty value
$temp2 = "'"; //starting quote
$temp2 .= str_replace(",", "','", $temp); //quotes around commas
$temp2 .= "'"; //ending quote
$result = $temp2; // = 'apples','bananas','oranges'
This should give you single-quote around the strings, but note that if some more values in the array are sometimes empty you will probably have to write a foreach loop and build the string.

Categories