This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
remove element from array based on its value?
I have this array
$arr = array(
'key1'=>'value1',
'key2'=>NULL,
'key3'=>'value2'
);
if I do implode(',',$arr); I get: value1,,value2 (notice the empty space)
Is there a way to skip that NULL values? To get something like this:
value1,value2
I could traverse all the array and unset manually the key where the value is NULL, but it's a bit an overkill doens't it?
Edit:
To save time Maybe I could do just one loop to iterate over the array, and in the same loop I check for null values and if isn't null I append it the ','
like this:
foreach($arr as $k=>$v) {
if ($v !== NULL) {
echo $v.',';
}
}
The problem here is that I have a final ',' at the end.
Edit
As gordon asked, it ran this test (1000000 iterations)
First using array_filter:
$pairsCache = array('key1'=>'value1','key2'=>NULL,'key3'=>'value3',
'key4'=>'value4','key5'=>'value5');
for($i=0;$i<1000000;$i++) {
$query = "INSERT INTO tbl (";
$keys='';
$values='';
$pairs = array_filter($pairsCache,function($v){return $v !== NULL;});
$keys = array_keys($pairs);
//> keys
$query .= implode(',',$keys ) . ") VALUES ( '";
//> values
$query .= implode("','",$pairs) . "')";
}
Time: 7.5949399471283
Query: "INSERT INTO tbl (key1,key3,key4,key5) VALUES ( 'value1','value3','value4','value5')"
Second using only one loop:
for($i=0;$i<1000000;$i++) {
$query = "INSERT INTO tbl (";
$keys='';
$values='';
foreach($pairsCache as $k=>$v) {
if ($v!==NULL) {
$keys .= $k.',';
$values .= "'{$v}',";
}
}
$keys=rtrim($keys,',');
$values=rtrim($values,',');
$query = $query . $keys . ') VALUES ( ' . $values . ')';
}
Time: 4.1640941333771
Query: INSERT INTO tbl (key1,key3,key4,key5,) VALUES ( 'value1','value3','value4','value5')
$arr = array_filter($arr);
array_filter() removes every value, that evaluates to false from $arr.
If you need finer control, you can pass a callback as second argument
arr = array_filter($arr, function ($item) { return !is_null($item);});
At last of course you can iterate over the array yourself
foreach (array_keys($arr) $key) {
if (is_null($arr[$key])) unset($arr[$key]);
}
Note, that there is no downside, if you filter and output in two separate steps
You can use array_filter():
If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.
implode(',', array_filter($arr));
There is no possibility to do this using only implode().
You can traverse all the array (as you said) maybe in a wrapper my_implode() function, or you can use something less elegant such as:
trim(preg_replace('/[,]+/', ',', implode(',', $arr)), ',');
You can simply use bellow code.
Edited.
function nullFilter($val)
{
return $val !== NULL;
}
$arr = array( 'key1'=>'value1', 'key2'=>NULL, 'key3'=>'value2' );
$filteredArray = array_filter($arr,"nullFilter");
echo implode(',', $filteredArray);
Cheers!
Prasad.
Related
I have an array like this,
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
I want to find any value with an ">" and replace it with a range().
The result I want is,
array(
1,2,3,4,5,6,7,8,9,10,11,12, '13.1', '13.2', 14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30
);
My understanding:
if any element of $array has '>' in it,
$separate = explode(">", $that_element);
$range_array = range($separate[0], $separate[1]); //makes an array of 4 to 12.
Now somehow replace '4>12' of with $range_array and get a result like above example.
May be I can find which element has '>' in it using foreach() and rebuild $array again using array_push() and multi level foreach. Looking for a more elegant solution.
You can even do it in a one-liner like this:
$array = array(1,2,3,'4>12','13.1','13.2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,#range(...array_slice(explode(">","$c>$c"),0,2)));},
[]
));
I avoid any if clause by using range() on the array_slice() array I get from exploding "$c>$c" (this will always at least give me a two-element array).
You can find a little demo here: https://rextester.com/DXPTD44420
Edit:
OK, if the array can also contain non-numeric values the strategy needs to be modified: Now I will check for the existence of the separator sign > and will then either merge some cells created by a range() call or simply put the non-numeric element into an array and merge that with the original array:
$array = array(1,2,3,'4>12','13.1','64+2','14>30');
print_r(array_reduce(
$array,
function($a,$c){return array_merge($a,strpos($c,'>')>0?range(...explode(">",$c)):[$c]);},
[]
));
See the updated demo here: https://rextester.com/BWBYF59990
It's easy to create an empty array and fill it while loop a source
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$res = [];
foreach($array as $x) {
$separate = explode(">", $x);
if(count($separate) !== 2) {
// No char '<' in the string or more than 1
$res[] = $x;
}
else {
$res = array_merge($res, range($separate[0], $separate[1]));
}
}
print_r($res);
range function will help you with this:
$array = array(
1,2,3,'4>12','13.1','13.2','14>30'
);
$newArray = [];
foreach ($array as $item) {
if (strpos($item, '>') !== false) {
$newArray = array_merge($newArray, range(...explode('>', $item)));
} else {
$newArray[] = $item;
}
}
print_r($newArray);
This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
Ok, I know that to get a comma-seperated string from a string array in PHP you could do
$stringA = array("cat","dog","mouse");
$commaSeperatedS = join(',', $stringA);
But what if I have an array of arrays(not a simple string array)?
$myAssociativeA =
array(
[0] => array("type"=>"cat", "sex"=>"male")
, [1] => array("type"=>"dog", "sex"=>"male")
);
and my goal is to get a comma-seperated string from a specific property in each array, such as "type"? Ive tried
$myGoal = join(',', $myAssociativeA{'type'});
My target value for $myGoal in this case would be "cat,dog".
Is there a simple way without having to manually loop through each array, extract the property, then do a join at the end?
This should work for you:
(Here I just get the column which you want with array_column() and simply implode it with implode())
echo implode(",", array_column($myAssociativeA, "type"));
Another option is to use array_walk() to return the key you want:
array_walk($myAssociativeA, function(&$value, $key, $return) {
$value = $value[$return];
}, 'type');
echo implode(', ', $myAssociativeA); // cat, dog
Useful for older PHP versions - #Rizier123's answer using array_column() is great for PHP 5.5.0+
You can use this if you have PHP < 5.5.0 and >= 5.3.0 (thanks to #Rizier123) and you can't use array_column()
<?php
$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$myGoal = implode(',', array_map(function($n) {return $n['type'];}, $myAssociativeA));
echo $myGoal;
?>
EDIT: with the recommendation in the comment of #scrowler the code now is:
<?php
$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$column = 'type';
$myGoal = implode(',', array_map(function($n) use ($column) {return $n[$column];}, $myAssociativeA));
echo $myGoal;
?>
Output:
cat,dog
Read more about array_map in:
http://php.net/manual/en/function.array-map.php
You just have to loop over the array and generate the string yourself.
<?php
$prepend = '';
$out = '';
$myAssociativeA = array(
array('type' => 'cat'),
array('type' => 'dog')
);
foreach($myAssociativeA as $item) {
$out .= $prepend.$item['type'];
$prepend = ', ';
}
echo $out;
?>
You could easily turn this into a function.
<?php
function implode_child($array,$key) {
$prepend = '';
$out = '';
foreach($array as $item) {
$out .= $prepend.$item[$key];
$prepend = ', ';
}
return $out;
}
?>
Ok, under assumption that your assoc array fields are ordered always the same way you could use snippet like this. Yet you still need to iterate over the array.
$csvString = "";
foreach ( $myAssociativeA as $row ) {
$csvRow = implode(",", $row);
$csvString .= $csvRow . PHP_EOL;
}
Now if you don't want to store whole CSV in a variable (which you should not do) take a look at http://www.w3schools.com/php/func_filesystem_fputcsv.asp and see an example how to put it directly into the file.
I have a page with a form where I post all my checkboxes into one array in my database.
The values in my database looks like this: "0,12,0,15,58,0,16".
Now I'm listing these numbers and everything works fine, but I don't want the zero values to be listed on my page, how am I able to search through the array and NOT list the zero values ?
I'm exploding the array and using a for each loop to display the values at the moment.
The proper thing to do is to insert a WHERE statement into your database query:
SELECT * FROM table WHERE value != 0
However, if you are limited to PHP just use the below code :)
foreach($values AS $key => $value) {
//Skip the value if it is 0
if($value == 0) {
continue;
}
//do something with the other values
}
In order to clean an array of elements, you can use the array_filter method.
In order to clean up of zeros, you should do the following:
function is_non_zero($value)
{
return $value != 0;
}
$filtered_data = array_filter($data, 'is_non_zero');
This way if you need to iterate multiple times the array, the zeros will already be deleted from them.
you can use array_filter for this. You can also specify a callback function in this function if you want to remove items on custom criteria.
Maybe try:
$out = array_filter(explode(',', $string), function ($v) { return ($v != 0); });
There are a LOT of ways to do this, as is obvious from the answers above.
While this is not the best method, the logic of this might be easier for phpnewbies to understand than some of the above methods. This method could also be used if you need to keep your original values for use in a later process.
$nums = '0,12,0,15,58,0,16';
$list = explode(',',$nums);
$newList = array();
foreach ($list as $key => $value) {
//
// if value does not equal zero
//
if ( $value != '0' ) {
//
// add to newList array
//
$newList[] = $value;
}
}
echo '<pre>';
print_r( $newList );
echo '</pre>';
However, my vote for the best answer goes to #Lumbendil above.
$String = '0,12,0,15,58,0,16';
$String = str_replace('0', '',$String); // Remove 0 values
$Array = explode(',', $String);
foreach ($Array AS $Values) {
echo $Values."<br>";
}
Explained:
You have your checkbox, lets say the values have been converted into a string. using str_replace we have removed all 0 values from your string. We have then created an array by using explode, and using the foreach loop. We are echoing out all the values of th array minux the 0 values.
Oneliner:
$string = '0,12,0,15,58,0,16';
echo preg_replace(array('/^0,|,0,|,0$/', '/^,|,$/'), array(',', ''), $string); // output 12,15,58,16
Edit: The aim of my method is to delete a value from a string in a database.
I cant seem to find the answer for this one anywhere. Can you concatenate inside a str_replace like this:
str_replace($pid . ",","",$boom);
$pid is a page id, eg 40
$boom is an exploded array
If i have a string: 40,56,12 i want to make it 56,12 however without the concatenator in it will produce:
,56,12
When I have the concat in the str_replace it doesnt do a thing. Is this possible?
Answering your question: yes you can. That code works as you would expect it to.
But this approach is wrong. It will not work for $pid = 12; (last element, without trailing coma) and will incorrectly replace 40, in $boom = '140,20,12';
You should keep it in array, search for unwanted value, if found unset it from the array and then implode with coma.
$boom = array_filter($boom);
$key = array_search($pid, $boom);
if($key !== false){
unset($boom[$key]);
}
$boom = implode(',',$boom);
[+] Your code does not work because $boom is an array, and str_replace operates on string.
As $boom is an array, you don't need to use array on your case.
Change this
$boom = explode(",",$ticket_array);
$boom = str_replace($pid . ",","",$boom);
$together = implode(",",$boom);
to
$together = str_replace($pid . ",","",$ticket_array);
Update: If you want still want to use array
$boom = explode(",",$ticket_array);
unset($boom[array_search($pid, $boom)]);
$together = implode(",",$boom);
After you have edited it becomes clear that you want to remove the value of $pid from the array $boom which contains one number as a value. You can use array_search to find if it is in at if in with which key. You can then unset the element from $boom:
$pid = '40';
$boom = explode(',', '40,56,12');
$r = array_search($pid, $boom, FALSE);
if ($r !== FALSE) {
unset($boom[$r]);
}
Old question:
Can you concatenate inside a str_replace like this: ... ?
Yes you can, see the example:
$pid = '40';
$boom = array('40,56,12');
print_r(str_replace($pid . ",", "", $boom));
Result:
Array
(
[0] => 56,12
)
Which is pretty much like you did so you might be looking for the problem at the wrong place. You can use any string expression for the parameter.
It might be easier for you if you're unsure to create a variable first:
$pid = '40';
$boom = array('40,56,12');
$search = sprintf("%d,", $pid);
print_r(str_replace($search, "", $boom));
You should store your "ticket array" in a separate table.
And use regular SQL queries (UPDATE, DELETE) to manipulate it.
A relational word in the name of your database is for the reason. And you are abusing this smart software with such a barbaric approach.
You could use str_split, it converts a string to an array, then with a foreach loop echo all the values except the first one.
$numbers_string="40,56,12";
$numbers_array = str_split($numbers_string);
//then, when you have the array of numbers, you could echo every number except the first separating them with a comma
foreach ($numbers_array as $key => $value) {
if ($key > 0) {
echo $value . ", ";
}
}
If you want is to skip a value not by it's position in the array, but for it's value then you could do this instead:
$unwanted_value="40";
foreach ($numbers_array as $key => $value) {
if ($value != $unwanted_value) {
echo $value . ", ";
}
else {
unset($numbers_array[$key]);
$numbers_array = array_values($numbers_array);
var_dump($numbers_array);
}
}
I have an array holding this data:
Array (
[1402377] => 7
[1562441] => 7
[1639491] => 9
[1256074] => 10
)
How can create a string that contains the keys of the above array?
Essentially, I need to create a comma separated string that consists of an array's keys
The string would look like: 'key','key','key'
Do I need to create a new array consisting of the keys from an existing array?
The reason I need to do this is because I will be querying a MySQL database using a WHERE in () statement. I would rather not have to query the database using a foreach statement. Am I approaching this problem correctly?
I've tried using a while statement, and I'm able to print the array keys that I need, but I need those keys to be an array in order to send to my model.
The code that allowed me to print the array keys looks like this:
while($element = current($array)) {
$x = key($array)."\n";
echo $x;
next($array);
}
$string = implode(',', array_keys($array));
By the way, for looping over an array consider not using current and next but use foreach:
foreach ($array as $key => $value) {
//do something
}
This will automatically iterate over the array until all records have been visited (or not at all if there are no records.
$keys = array_keys($array);
$string = implode(' ',$keys);
In your case, were you are using the result in a IN clause you should do:
$string = implode(',', $keys);
$yourString = '';
foreach($yourArr as $key => $val) {
$yourString .=$key.",";
}
echo rtrim($yourString, ",");
//OR
$yourString = implode(",", array_keys($yourArray));
See : array_keys
implode(', ', array_keys($array));
Use php array_keys and implode methods
print implode(PHP_EOL, array_keys($element))
The string would look like: 'key','key','key'
$string = '\'' . implode('\',\'', array_keys($array)) . '\'';
Imploding the arguments and interpolating the result into the query can cause an injection vulnerability. Instead, create a prepared statement by repeating a string of parameter placeholders.
$paramList = '(' . str_repeat('?, ', count($array) - 1) . '?)'
$args = array_keys($array);
$statement = 'SELECT ... WHERE column IN ' . $paramList;
$query = $db->prepare($statement);
$query->execute($args);