Related
I want to insert a new line after n commas.
For example I got this value: 385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426
How I could echo them all, but every 5th comma there should be a linebreak?
385,386,387,388,389,
390,391,392,393,394,
395,396,397,398,399,
400,401,402,403,404,
405,406,407,408,409,
410,411,412,413,414,
415,416,417,418,419,
420,421,422,423,424,
425,426
Here's one method:
// Get all numbers
$numbers = explode(',', $str);
// Split into groups of 5 (n)
$lines = array_chunk($numbers, 5);
// Format each line as comma delimited
$formattedLines = array_map(function ($row) { return implode(',', $row); }, $lines);
// Format groups into new lines with commas at the end of each line (except the last)
$output = implode(",\n", $formattedLines);
Try this
<?php
//Start //Add this code if your values in string like that
$string = "385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426";
$string_array = explode(',', $string);
//End //Add this code if your values in string like that
//If you have values in array then direct use below code skip above code and replace $string_array variable with yours
end($string_array);
$last = key($string_array);
foreach ($string_array as $key => $value) {
if($last==$key){
echo $value;
}else{
echo $value.',';
}
if(($key+1)%5==0){
echo "<br />";
}
}
?>
Try like this.
You can explode the string with commas and check for every 5th
position there should be a line break.
You can check it with dividing key with 5.(i.e) it will give you a
remainder of 0
Please note that key starts from 0, so I have added (key+1), to make it start from 1
$string = "385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426";
$stringexplode = explode(",", $string);
$countstringexplode = count($stringexplode);
foreach($stringexplode as $key => $val)
{
$keyIncrement = $key+1;
echo $val.($countstringexplode == $keyIncrement ? "" : ",") ;
if(($keyIncrement) % 5 == 0)
echo "<br>";
}
?>
So my question might not be the best, so sorry for that.
I have an array with strings and want to write a text with the help of another array using it as the order/key. This is the Input:
$words =["I","am","cool"];
$order =["2","0","1","0","1","2"];
//var_export($words);
// array (
// 0 => 'I',
// 1 => 'am',
// 2 => 'cool',
// )
I want to use $order as some sort of key to rearrange $words so I can get this Output:
"Cool I am I am cool"
Help is much appreciated, thank you :)
Use the values of $order as the keys for $words.
$words =["I","am","cool"];
$order =["2","0","1","0","1","2"];
$output = '';
foreach($order as $key) {
$output .= $words[$key] . ' ';
}
echo ucfirst(trim($output));
Demo: https://eval.in/780785
The empty($real_key) is to check if it is the first iteration. Also could be == 0.
I would recommend the use of array_map and join
There is no need for
side-effecting manual iteration using foreach
if statements or ternary (?:) expressions
variable reassignment
string concatenation using .
checking array lengths
Here we go
function map_indexes_to_words ($indexes, $words) {
$lookup = function ($i) use ($words) {
return $words[(int) $i];
};
return join(' ', array_map($lookup, $indexes));
}
$words = ["I","am","cool"];
$order = ["2","0","1","0","1","2"];
echo map_indexes_to_words($order, $words);
// 'cool I am I am cool'
Start with an empty array.
Then loop through the order array and add the word array part to the new string.
$my_string= array();
foreach ( $order as $index ) {
$index = int($index);
$my_string[] = ( isset($words[ $index]) ) ? $words[ $index ] : '' );
}
$my_string = implode(' ', $my_string);
echo my_string;
Iterate over order and use it's values as keys to words; Convert the following code to php it should be pretty simple...
foreach (string orderIndexString in order) {
int orderIndexInt = System.Convert.ToInt16(orderIndexString); // convert string to int
if(orderIndexInt < 0 || orderIndexInt >= words.Length)
continue;
print (words[orderIndexInt]); // either print or add it to another string
}
I have a variable with multiple number stored as a string:
$string = "1, 2, 3, 5";
and multidimensional array with other stored values:
$ar[1] = array('title#1', 'filename#1');
$ar[2] = array('title#2', 'filename#2');
$ar[3] = array('title#3', 'filename#3');
$ar[4] = array('title#4', 'filename#4');
$ar[5] = array('title#5', 'filename#5');
My goal is to replace number from $string with related tiles from $ar array based on associated array key. For an example above I should to get:
$string = "title#1, title#2, title#3, title#5";
I have tried to loop through $ar and do str_replace on $string, but final value of $string is always latest title from related array.
foreach($ar as $key => $arr){
$newString = str_replace($string,$key,$arr[0]);
}
Any tips how to get this solved?
Thanks
you can do it by str_replace by concat each time or you can do it by explode and concat.
Try Like this:
$string = "1, 2, 3, 5";
$arrFromString = explode(',', $string);
$newString = '';
foreach($ar as $intKey => $arr){
foreach($arrFromString as $intNumber){
if($intKey == $intNumber) {
$newString .= $arr[0].',';
}
}
}
$newString = rtrim($newString,',');
echo $newString;
Output:
title#1,title#2,title#3,title#5
live demo
You can use explode() and implode() functions to get the numbers in $string as an array and to combine the titles into a string respectively:
$res = array();
foreach (explode(", ", $string) as $index) {
array_push($res, $ar[$index][0]);
}
$string = implode(", ", $res);
print_r($string);
will give you
title#1, title#2, title#3, title#5;
I'm currently printing table column names, filtered, but need to change the text for each.
For instance, the following:
$row = mysql_fetch_assoc($query_columns);
echo implode(', ', array_keys( array_filter( $row )));
outputs:
column_one, column_two, column_five
What I haven't been able to achieve, without a lengthy if statement, is a way to have complete control over the output, such as changing each...
Expected output:
This is column one, and Column two, but this is column five
Any help is much appreciated!
Table structure:
Category
--------
user_id
live_out
live_in
short_term
weekday
weekend
unsure
Current output (based on user selection):
live_out, live_in, weekday
Desired output:
Yes as live-out, Yes as live-in, Yes for regular weekdays
You have echo implode(', ', array_keys( array_filter( $row )));
The implode() uses the array to concatenate the keys to one string.
One solution would be to use string concatenation, when iterating the array:
$array = array_keys( array_filter( $row ))); // gets you the keys array
$string = 'This is ';
foreach($array as $item)
{
$string .= $item . ', '; // append item to string with comma added
}
$string .= '. That's all.';
echo $string;
If you want custom text per item, you need to detect the item when iterating.
You might use if and strpos() for that, like so:
$string = 'This is ';
foreach($array as $item)
{
$string .= $item . ', '; // append item to string with comma added
if(false !== strpos($item, 'Column One')) { // look for Column One in $item
$string .= ' (found column one)';
}
}
$string .= ' That's all.';
echo $string;
Replace:
$string = str_replace('Column One', 'Column XXX', $string);
works also for multiple items at once
$replace = array('Column One', 'Column Two');
$with = array('Column XX1', 'Column XX2');
$string = str_replace($replace, $with, $string);
Take care about $string = and $string .=.
The first assigns the value, the second appends the value.
Based on your table structure
$string = '';
foreach($array as $item)
{
if(false !== strpos($item, 'live_out')) {
$string .= 'Yes for '. $item . ', ';
}
if(false !== strpos($item, 'live_in')) {
$string .= 'Yes for '. $item . ', ';
}
if(false !== strpos($item, 'weekdays')) {
$string .= 'Yes for regular '. $item;
}
}
echo $string;
You can change each item in the array like this;
$column_names[0] = "Add this to the start of column one ". $column_names[0] . ", and this to the end of column one.";
0 is the first item in the array, and 1 is the second and so on.
Remember you need to do this to the array you get from array_keys in this case.
Otherwise you could make a function like this;
function addStrToArrayElements($array, $str_start, $str_end, $array_keys=NULL){
foreach($array as $key => $item){
if(array_key_exists($key, $array_keys) || is_null($array_keys) ){
$ret[$key] = $str_start.$item.$str_end;
}
}
return $ret;
}
$array is the array you want the elements to change on, $str_start is the string to put in front of the item, $str_end the on behind the item, and $array_keys is an array of the keys of which elements you want changed, if you leave it blank, it will do the same to all elements of $array.
For the example you have above you would do this:
$column_names = array_keys($row);
addStrToArrayElements($column_names, 'This is ', ',', array(0));
addStrToArrayElements($column_names, ' and ', ',', array(1));
addStrToArrayElements($column_names, ' but this is ', '', array(2));
$output = implode('', $column_names);
echo str_replace('column_', 'column ', $output);
That should output
This is column one, and column two, but this is column five
Say you have the following array called $array1 below:
<?php
$array1 = array("hey","its","me","so","what");
$newarray = array();
$i=0;
foreach ($array1 as $value)
{
$newarray[] = "<span id=" . "color$i" . ">" . $value . "</span>";
$i++;
}
echo implode(",",$newarray);
?>
You can use the algorithm to set different styles for all the columns using the spans created. So for instance you can set a style in the head or external stylesheet like so:
<style>
#color0{ color:red;}
#color1{ color:blue;}
#color2{ color:yellow;}
</style>
I tested this out and it seems to work just fine!
This array holds a list of items, and I want to turn it into a string, but I don't know how to make the last item have a &/and before it instead of a comma.
1 => coke 2=> sprite 3=> fanta
should become
coke, sprite and fanta
This is the regular implode function:
$listString = implode(', ', $listArrau);
What's an easy way to do it?
A long-liner that works with any number of items:
echo join(' and ', array_filter(array_merge(array(join(', ', array_slice($array, 0, -1))), array_slice($array, -1)), 'strlen'));
Or, if you really prefer the verboseness:
$last = array_slice($array, -1);
$first = join(', ', array_slice($array, 0, -1));
$both = array_filter(array_merge(array($first), $last), 'strlen');
echo join(' and ', $both);
The point is that this slicing, merging, filtering and joining handles all cases, including 0, 1 and 2 items, correctly without extra if..else statements. And it happens to be collapsible into a one-liner.
I'm not sure that a one liner is the most elegant solution to this problem.
I wrote this a while ago and drop it in as required:
/**
* Join a string with a natural language conjunction at the end.
* https://gist.github.com/angry-dan/e01b8712d6538510dd9c
*/
function natural_language_join(array $list, $conjunction = 'and') {
$last = array_pop($list);
if ($list) {
return implode(', ', $list) . ' ' . $conjunction . ' ' . $last;
}
return $last;
}
You don't have to use "and" as your join string, it's efficient and works with anything from 0 to an unlimited number of items:
// null
var_dump(natural_language_join(array()));
// string 'one'
var_dump(natural_language_join(array('one')));
// string 'one and two'
var_dump(natural_language_join(array('one', 'two')));
// string 'one, two and three'
var_dump(natural_language_join(array('one', 'two', 'three')));
// string 'one, two, three or four'
var_dump(natural_language_join(array('one', 'two', 'three', 'four'), 'or'));
It's easy to modify to include an Oxford comma if you want:
function natural_language_join( array $list, $conjunction = 'and' ) : string {
$oxford_separator = count( $list ) == 2 ? ' ' : ', ';
$last = array_pop( $list );
if ( $list ) {
return implode( ', ', $list ) . $oxford_separator . $conjunction . ' ' . $last;
}
return $last;
}
You can pop last item and then join it with the text:
$yourArray = ('a', 'b', 'c');
$lastItem = array_pop($yourArray); // c
$text = implode(', ', $yourArray); // a, b
$text .= ' and '.$lastItem; // a, b and c
Try this:
$str = array_pop($array);
if ($array)
$str = implode(', ', $array)." and ".$str;
Another possible short solution:
$values = array('coke', 'sprite', 'fanta');
$values[] = implode(' and ', array_splice($values, -2));
print implode(', ', $values); // "coke, sprite and fanta"
It works fine with any number of values.
My go-to, similar to Enrique's answer, but optionally handles the oxford comma.
public static function listifyArray($array,$conjunction='and',$oxford=true) {
$last = array_pop($array);
$remaining = count($array);
return ($remaining ?
implode(', ',$array) . (($oxford && $remaining > 1) ? ',' : '') . " $conjunction "
: '') . $last;
}
I know im way to late for the answer, but surely this is a better way of doing it?
$list = array('breakfast', 'lunch', 'dinner');
$list[count($list)-1] = "and " . $list[count($list)-1];
echo implode(', ', $list);
This can be done with array_fill and array_map. It is also a one-liner (seems that many enjoy them)), but formated for readability:
$string = implode(array_map(
function ($item, $glue) { return $item . $glue; },
$array,
array_slice(array_fill(0, count($array), ', ') + ['last' => ' and '], 2)
));
Not the most optimal solution, but nevertheless.
Here is the demo.
try this
$arr = Array("coke","sprite","fanta");
$str = "";
$lenArr = sizeof($arr);
for($i=0; $i<$lenArr; $i++)
{
if($i==0)
$str .= $arr[$i];
else if($i==($lenArr-1))
$str .= " and ".$arr[$i];
else
$str .= " , ".$arr[$i];
}
print_r($str);
Try this,
<?php
$listArray = array("coke","sprite","fanta");
foreach($listArray as $key => $value)
{
if(count($listArray)-1 == $key)
echo "and " . $value;
else if(count($listArray)-2 == $key)
echo $value . " ";
else
echo $value . ", ";
}
?>
I just coded this based on the suggestions on this page. I left in my pseudo-code in the comments in case anyone needed it. My code differs from others here as it handles different-sized arrays differently and uses the Oxford comma notation for lists of three or more.
/**
* Create a comma separated list of items using the Oxford comma notation. A
* single item returns just that item. 2 array elements returns the items
* separated by "and". 3 or more items return the comma separated list.
*
* #param array $items Array of strings to list
* #return string List of items joined by comma using Oxford comma notation
*/
function _createOxfordCommaList($items) {
if (count($items) == 1) {
// return the single name
return array_pop($items);
}
elseif (count($items) == 2) {
// return array joined with "and"
return implode(" and ", $items);
}
else {
// pull of the last item
$last = array_pop($items);
// join remaining list with commas
$list = implode(", ", $items);
// add the last item back using ", and"
$list .= ", and " . $last;
return $list;
}
}
This is quite old at this point, but I figured it can't hurt to add my solution to the pile. It's a bit more code than other solutions, but I'm okay with that.
I wanted something with a bit of flexibility, so I created a utility method that allows for setting what the final separator should be (so you could use an ampersand, for instance) and whether or not to use an Oxford comma. It also properly handles lists with 0, 1, and 2 items (something quite a few of the answers here do not do)
$androidVersions = ['Donut', 'Eclair', 'Froyo', 'Gingerbread', 'Honeycomb', 'Ice Cream Sandwich', 'Jellybean', 'Kit Kat', 'Lollipop', 'Marshmallow'];
echo joinListWithFinalSeparator(array_slice($androidVersions, 0, 1)); // Donut
echo joinListWithFinalSeparator(array_slice($androidVersions, 0, 2)); // Donut and Eclair
echo joinListWithFinalSeparator($androidVersions); // Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwich, Jellybean, Kit Kat, Lollipop, and Marshmallow
echo joinListWithFinalSeparator($androidVersions, '&', false); // Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwich, Jellybean, Kit Kat, Lollipop & Marshmallow
function joinListWithFinalSeparator(array $arr, $lastSeparator = 'and', $oxfordComma = true) {
if (count($arr) > 1) {
return sprintf(
'%s%s %s %s',
implode(', ', array_slice($arr, 0, -1)),
$oxfordComma && count($arr) > 2 ? ',':'',
$lastSeparator ?: '',
array_pop($arr)
);
}
// not a fan of this, but it's the simplest way to return a string from an array of 0-1 items without warnings
return implode('', $arr);
}
OK, so this is getting pretty old, but I have to say I reckon most of the answers are very inefficient with multiple implodes or array merges and stuff like that, all far more complex than necessary IMO.
Why not just:
implode(',', array_slice($array, 0, -1)) . ' and ' . array_slice($array, -1)[0]
Simple human_implode using regex.
function human_implode($glue = ",", $last = "y", $elements = array(), $filter = null){
if ($filter) {
$elements = array_map($filter, $elements);
}
$str = implode("{$glue} ", $elements);
if (count($elements) == 2) {
return str_replace("{$glue} ", " {$last} ", $str);
}
return preg_replace("/[{$glue}](?!.*[{$glue}])/", " {$last}", $str);
}
print_r(human_implode(",", "and", ["Joe","Hugh", "Jack"])); // => Joe, Hugh and Jack
Another, although slightly more verbose, solution I came up with. In my situation, I wanted to make the words in the array plural, so this will add an "s" to the end of each item (unless the word already ends in 's':
$models = array("F150","Express","CR-V","Rav4","Silverado");
foreach($models as $k=>$model){
echo $model;
if(!preg_match("/s|S$/",$model))
echo 's'; // add S to end (if it doesn't already end in S)
if(isset($models[$k+1])) { // if there is another after this one.
echo ", ";
if(!isset($models[$k+2]))
echo "and "; // If this is next-to-last, add ", and"
}
}
}
outputs:
F150s, Express, CR-Vs, Rav4s, and Silverados
It's faster then deceze's solution and works with huge arrays (1M+ elements). The only flaw of both solutions is a poor interaction with a number 0 in a less then three elements arrays becouse of array_filter use.
echo implode(' and ', array_filter(array_reverse(array_merge(array(array_pop($array)), array(implode(', ',$array))))));