Convert string to array and perform foreach, codeigniter - php

I would like some help in converting a string to an array and performing foreach on the array data.
Currently in my view I echo my string <?php echo $p['tags']; ?>
and this gives me the following data news, latest
I would like to do a foreach on this data so that I can wrap the values in
How is this done? What is the best method?

Explode them into an array:
<?php
$all_tags = explode( ',' , $p['tags'] );
foreach ( $all_tags as $one_tag ){
echo '' . $one_tag . '';
}
The explode() function splits the string using a delimiter (in this case the ',' comma) and each item is passed into the array.

I'm not sure I understand what you're asking correctly. Is this what you want?
$var = 'news, lastest';
$tmp = explode(', ', $var);
$result = ''.implode(', ', $tmp).'';
var_dump($result);
// string(42) "news, lastest"

Related

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'

How to remove last character from a string inside a loop

I am trying to print the different category's selected in a single line in xml,
like
<cat_name>meeting, food and drinks, sports</cat_name>
The output I am getting:
<cat_name>meeting, food and drinks, sports,</cat_name>
I want to remove only the last comma.
The code I have written so far is:
$sq="
select category_main.cat_name
from category_main
join category
on(category.cat_id=category_main.cat_id)
where category.event_id='$event_id'
";
$e=mysql_query($sq);
$xml ='<cat_name>';
while($row=mysql_fetch_array($e))
{
$res=$row['cat_name'];
//$new = substr($val,0,-1);
$xml .="$res, ";
}
$xml .='</cat_name>';
echo $xml;
Call trim() with the optional second parameter as a ','
trim($cat_name, ',')
However, since you're doing this in a while loop, you should build an array then implode() it rather than building the string in the loop. This avoids the extra comma to begin with.
$arr = array();
while($row=mysql_fetch_array($e))
{
$arr[] = $row['cat_name'];
}
$cat_name = implode(",", $arr);
// $cat_name is now "meeting, food and drinks, sports"
You can do this by [i used my variable]
$str = substr($str,0, (strlen($str)-1));
Or use a rtrim, rtrim( $cat , ',' ) http://php.net/rtrim

separate with commas

hey there I have this,
$following_user_id .= $row['following_user_id'];
and I get
44443344330
then I use the implode() function and seperate with commans
44,44,33,44,33,0,
but I don't want the last comma on the last number?
Is this possible?
$following_user_ids = array();
//loop this:
$following_user_ids[] = $row['following_user_id'];
$user_ids_string = implode(',',$following_user_ids);
You can split the string into an array of characters, then implode the array.
$array = preg_split('//', $following_user_id, -1, PREG_SPLIT_NO_EMPTY);
echo implode( ',', $array );
Collect your data into an array of strings and use the implode function:
$uids = array();
while($row = mysql_fetch_assoc($result)){
array_push($uids, $row['following_user_id']);
}
$following_user_id = implode(',', $uids);
Check implode: http://php.net/manual/en/function.implode.php
Code example: I'm assuming your using some sort of loop?
$arrUsers = new array();
... your loop code here ...
array_push($arrUsers, $row['following_user_id']);
... end loop code ..
$following_user_id = impload(",", $arrUsers);
Implode should not be inserting a comma at the end of that string there. Are you sure there isn't an empty string at the end of your array sequence?
Either way, to fix the string you have, just get rid of the last character of the string:
$concatUserIds = "44,44,33,44,33,0,";
$concatUserIds = substr($concatUserIds, 0, strlen($concatUserIds) - 1);
Further, if you're not going to be using the non-comma delimited number set, why don't you just add a comma every time you add a user id. That way you don't even have to use the implode function.
This works for me:
<?php
$following_user_id.= $row['following_user_id'];
$following_user_id=preg_replace('/(?<=\d)(?=(\d)+(?!\d))/',',',$following_user_id);
echo $following_user_id."<br>";
?>
Try using arrays, example
<?php
$arr = array();
$arr[] = 'foo';
$arr[] = 'bar';
echo implode(',', $arr);

How do I place a comma between each character in a string with PHP? [duplicate]

hey there I have this,
$following_user_id .= $row['following_user_id'];
and I get
44443344330
then I use the implode() function and seperate with commans
44,44,33,44,33,0,
but I don't want the last comma on the last number?
Is this possible?
$following_user_ids = array();
//loop this:
$following_user_ids[] = $row['following_user_id'];
$user_ids_string = implode(',',$following_user_ids);
You can split the string into an array of characters, then implode the array.
$array = preg_split('//', $following_user_id, -1, PREG_SPLIT_NO_EMPTY);
echo implode( ',', $array );
Collect your data into an array of strings and use the implode function:
$uids = array();
while($row = mysql_fetch_assoc($result)){
array_push($uids, $row['following_user_id']);
}
$following_user_id = implode(',', $uids);
Check implode: http://php.net/manual/en/function.implode.php
Code example: I'm assuming your using some sort of loop?
$arrUsers = new array();
... your loop code here ...
array_push($arrUsers, $row['following_user_id']);
... end loop code ..
$following_user_id = impload(",", $arrUsers);
Implode should not be inserting a comma at the end of that string there. Are you sure there isn't an empty string at the end of your array sequence?
Either way, to fix the string you have, just get rid of the last character of the string:
$concatUserIds = "44,44,33,44,33,0,";
$concatUserIds = substr($concatUserIds, 0, strlen($concatUserIds) - 1);
Further, if you're not going to be using the non-comma delimited number set, why don't you just add a comma every time you add a user id. That way you don't even have to use the implode function.
This works for me:
<?php
$following_user_id.= $row['following_user_id'];
$following_user_id=preg_replace('/(?<=\d)(?=(\d)+(?!\d))/',',',$following_user_id);
echo $following_user_id."<br>";
?>
Try using arrays, example
<?php
$arr = array();
$arr[] = 'foo';
$arr[] = 'bar';
echo implode(',', $arr);

Feed parsing, splitting string

Say I have the following:
$cars = "auto1,auto2,auto3,auto4";
If I parse $cars to insert the value in my database, I get a string like "auto1,auto2,auto3,auto4".
I want to split this string when I parse the feed into "auto1, auto2, auto3, auto4" - basically add spaces between words. How can i do it?
Here's how I get values for $cars:
$xml = simplexml_load_file($feed);
foreach( $xml->feedinfo as $feedinfo )
{
$cars = $feedinfo->cars;
[...]
}
Thank you
If you just want to add spaces:
$cars = str_replace(',', ', ', $cars);
But you could also split it into an array of elements:
$cars = explode(',', $cars)

Categories