How can I add a variable to an array? - php

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

Related

How to store the string values into an array in php?

I have one parameter every time it comes from the request object in a standard order,I want to store that string into an array by splitting \for that i am using explode function it's throwing an error,please help me to explode with backslash
$obj = "App\Http\Data\User";
$array = explode("\",$obj);
You can use this:
$obj = "App\Http\Data\User";
$array = explode("\\",$obj);
print_r($array);
example here

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

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

array_map does not give an empty array

I have the below line which takes a string, explodes it to an array by ',' and then trims any whitespace for each array item.
$essentialArray = array_map('trim', explode(',', $essential_skills));
However when $essential_skills string = "" $essentialArray will equal Array ( [0] => )
But I need it to equal Array() so that I can call empty() on on it.
That is normal and logical behavior of the function.
Look at it this way: what does the explode() call return? An array with a single element which is the empty string. The array_map() call does not change that at all.
So you might ask: why does explode('') result in an array with a single element which is the empty string? Well, why not? It takes the empty string and splits it at all comma characters in there, so exactly no times. That means the empty string stays unaltered. But it does not magically vanish!
explode return Array ( [0] => ), so you need to check your string before array_map
here is a one solution
$exploderesult = $essential_skills ? explode(',', $essential_skills) : array();
$essentialArray = array_map('trim', $exploderesult );
The easiest solution here will be just filter result array, like this:
$essentialArray = array_filter(array_map('trim', explode(',', $essential_skills)));
but proper way is:
if ($essential_skills === '') {
$essentialArray = [];
}
else {
$essentialArray = array_map('trim', explode(',', $essential_skills));
}

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

Categories