Break apart an array in PHP - Convert to String - php

I have an array:
$arr['alpha'] = 'a';
$arr['beta'] = 'b';
$arr['delta'] = 'd';
Does anyone know if PHP has a function to take the above array and produce:
$some_string -- where $some_sting is set to the associative values of the array such that if I echoed $some_sting I would see:
"a,b,d"
Thanks.
I know how to write a for loop to produce the result, but I am curious if there is a simple function that already does this.

You can use implode()
Update:
About your comment under FreekOne's answer you wrote:
Ok, the answers herein are correct, but actually I stated the wrong outcome I am looking for. I actually want to yield "alpha,beta,delta". Is that possible?
This is how you do that..
<?php
function implode_key($glue = "", $pieces = array()) {
$arrK = array_keys($pieces);
return implode($glue, $arrK);
}
?>

$some_string = implode(',',$arr); //a,b,d
$some_string = implode(',',array_keys($arr)); //alpha,beta,delta

Use PHP's implode function:
http://php.net/manual/en/function.implode.php
Prototype:
string implode ( string $glue , array $pieces )
So you could do this:
$glued = implode(',' , $arr);

For the sake of variety, join() can also be used, but it's nothing more than an alias of the already suggested implode().
So, doing an echo join(',',$arr); would output a,b,c as well.

Related

Trim string with array using PHP

How can i trim with array of string in php. If I have an dynamic array as follows :
$arr = array(' ','<?php','?>',"'",'"');
so how can i use this array in trim() to remove those string, I tried very hard in the code below :
$text = trim(trim(trim(trim(trim($text),'<?php'),'?>'),'"'),"'");
but i can not use this because array is dynamic, it may have more than 1000 values.
It takes a lot of time to turn into a loop even after trying it.So I can do anything as follows
$text = trim($text, array(' ','<?php','?>',"'",'"') );
It's possible to apply trim() function to an array. The question seems to be unclear but you can use array_map(). Unclear because there are other enough possible solutions to replace substrings. To just apply trim() function to an array, use the following code.
$array = array(); //Your array
$trimmed_array = array_map('trim', $array); //Your trimmed array is here
If you also want to fulfill the argument requirement in trim() you can apply a custom anonymous function to array_map() like this:
$array = array(); //Your array
$trimmed_array = array_map(function($item){
return trim($item, 'characters to be stripped');
}, $array); //Your trimmed array is here

How to remove square bracket from an array?

I have an array..let say:
$array = [$a,$b,$c,$d];
How I can remove [ and ]?
The expected result would be:
$a,$b,$c,$d
I used some array function e.g array_slice but it does not fill my requirement. Any ideas?
Note: I need to pass all array elements to function as argument.
e.g: function example($a,$b,$c)
it sounds like you're after a string representation of the array, try using join() or implode() like this:
<?php
$array = [$a,$b,$c,$d];
$str = join(",", $array); // OR $str = implode(",", $array);
echo $str;
EDIT
after reading your question a little more carefully, you're trying to pass the array into a function call, to do that you need to use call_user_func_array():
<?php
function function_name($p1, $p2, $p3, $p4){
//do something here
}
$array = [$a,$b,$c,$d];
call_user_func_array('function_name', $array);

Put all explode arrays to one string

let's say I have a string called str, I dont know how long is that.
characters in the string are separated by '-' after each 16th character.
Now i called function like $ex = explode('-', $str);.
Now it is in array. I have changed some chracters in array. for example $ex[0][0] = 'a';
Now I want to connect that changed arrays back to variable $str2.
Something like $str2 = $ex[0].ex[1] but I don't know how long is that array.
Do you know how?
IF you didnt understand my explaination, tell me.
Thank you really much.
I think you want implode:
http://php.net/manual/en/function.implode.php
Example:
$str2 = implode('', $ex);
Try:
$str2 = implode('-', $ex);
This will take all of the elements of $ex and connect them into one string with the first parameter between each element. In this case: -.
If you don't want them to be connected by anything, then you can just do:
$str2 = implode($ex);
Use foreach. Foreach allows you to run through the array and automatically stop when the end has been reached.
An example would be:
foreach ($ex as $e) {
$str2 .= $e;
}

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

PHP: Concatenate array element into string with ',' as the separator

Is there a quick way ( existing method) Concatenate array element into string with ',' as the separator? Specifically I am looking for a single line of method replacing the following routine:
//given ('a','b','c'), it will return 'a,b,c'
private static function ConstructArrayConcantenate($groupViewID)
{
$groupIDStr='';
foreach ($groupViewID as $key=>$value) {
$groupIDStr=$groupIDStr.$value;
if($key!=count($groupViewID)-1)
$groupIDStr=$groupIDStr.',';
}
return $groupIDStr;
}
This is exactly what the PHP implode() function is for.
Try
$groupIDStr = implode(',', $groupViewID);
You want implode:
implode(',', $array);
http://us2.php.net/implode
implode()
$a = array('a','b','c');
echo implode(",", $a); // a,b,c
$arr = array('a','b','c');
$str = join(',',$arr);
join is an alias for implode, however I prefer it as it makes more sense to those from a Java or Perl background (and others).
implode() function is the best way to do this. Additionally for the shake of related topic, you can use explode() function for making an array from a text like the following:
$text = '18:09:00';
$t_array = explode(':', $text);
You can use implode() even with empty delimeter: implode(' ', $value); pretty convenient.

Categories