How to remove square bracket from an array? - php

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

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

str_replace with subject as associative array

I have an haystack that's an associative array:
$array['header']['title'] = 'MyTitle';
$array['header']['subtitle'] = 'MySubtitle';
$array['body'] = 'MyBody';
I'd wish to replace every occurrence of 'My' with 'Your'.
I'm trying something like this:
$new_array = str_replace('My', 'Your', $array);
Sadly it works only on the first level (ie body key).
Is there anything wrong? Is there a workaround?
array_walk_recursive($array, 'replaceMy');
function replaceMy(&$item) {
str_replace('My', 'Your', $item);
}
Try this one: array_walk_recursive
If your associative array is unknown, you will have to use a recursive method to go through it and do your replace if the value is a string.
Otherwise, use more calls:
$new_array = str_replace('My', 'Your', $array);
$new_array = str_replace('My', 'Your', $array['header']);

How can I add a variable to an array?

How can I add a variable to an array? Let say I have variable named $new_values:
$new_values=",543,432,888"
And now I would like to add $new_values to function. I tried in that way:
phpfunction1(array(114,763 .$new_values. ), $test);
but I got an error Parse error: syntax error, unexpected T_VARIABLE, expecting ')'
How my code should look if I would like to have array(114,763,543,432,888)?
$new_values=",543,432,888";
should be converted to an array:
$new_values= explode(',', "543,432,888");
and merged to existing values with:
array_merge(array(114,763), $new_values);
Whole code should looks like:
$new_values = explode(',', "543,432,888");
$values = array(114,763);
$values = array_merge($values, $new_values);
phpfunction1($values, $test);
If you pass to explode a string that is starting with , you will get first empty element, so avoid it.
if you have an array already i.e.
$values = array(543,432,888);
You can add to them by : $values[]=114; $values[]=763;
Apologies if I missed the point there...
In your example, $new_values is a string, but, since it's comma delimited, you can create an array directly from it. Use $new_array = explode(',', $new_values); to create an array from the string.
You need to convert the string into an array using the explode function and then use the array_merge function to merge the two arrays into one:
$new_values=",543,432,888";
$currentArray=array(114,763);
$newArray=array_merge($currentArray,explode(',',$new_values));
functionX($newArray...)
But watch out for the empty array element because of the first comma.
For that use "trim($new_values, ',')" - see answer from rajesh.
you can do like this.
$old_values = array(122,555);
$new_values=",543,432,888";
$values = explode(',', trim($new_values, ','));
$result = array_merge($old_values, $values);
print_r($result);
try array merge
looks like this
phpfunction1(array_merge(array(114,763) ,$new_values), $test);
and yes your first array is not an array
change it to this
$new_values=Array(543,432,888);

Break apart an array in PHP - Convert to String

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.

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