Serial comma from array in PHP - php

I am trying to make string serial comma from array. Here is the code I use:
<?php
echo "I eat " . implode(', ',array('satay','orange','rambutan'));
?>
But the results I get:
I eat satay, orange, rambutan
Cannot:
I eat satay, orange, and rambutan
Yet!
So, I made my own function:
<?php
function array_to_serial_comma($ari,$konj=" and ",$delimiter=",",$space=" "){
// If not array, then quit
if(!is_array($ari)){
return false;
};
$rturn=array();
// If more than two
// then do actions
if(count($ari)>2){
// Reverse array
$ariBlk=array_reverse($ari,false);
foreach($ariBlk as $no=>$c){
if($no>=(count($ariBlk)-1)){
$rturn[]=$c.$delimiter;
}else{
$rturn[]=($no==0)?
$konj.$c
: $space.$c.$delimiter;
};
};
// Reverse array
// to original
$rturn=array_reverse($rturn,false);
$rturn=implode($rturn);
}else{
// If >=2 then regular merger
$rturn=implode($konj,$ari);
};
// Return
return $rturn;
};
?>
Thus:
<?php
$eat = array_to_serial_comma(array('satay','orange','rambutan'));
echo "I eat $eat";
?>
Result:
I eat satay, orange, and rambutan
Is there a more efficient way, using a native PHP function maybe?
Edit:
Based on code from #Mash, I modifying the code that might be useful:
<?php
function array_to_serial_comma($ari,$konj=" and ",$delimiter=",",$space=" "){
// If not array, then quit
if(!is_array($ari)){
return false;
};
$rturn=array();
// If more than two
// then do actions
if(count($ari)>2){
$akr = array_pop($ari);
$rturn = implode($delimiter.$space, $ari) . $delimiter.$konj.$akr;
}else{
// If >=2 then regular merger
$rturn=implode($konj,$ari);
};
// Return
return $rturn;
};
?>

Here's a much cleaner way:
<?php
$array = array('satay','orange','rambutan');
$last = array_pop($array);
echo "I eat " . implode(', ', $array) . ", and " . $last;
?>
array_pop() takes the last element out of the array and assign it to $last

<?php
$arr = array('satay','orange','rambutan');
print("I eat ".implode(", ", array_slice($arr, 0, count($arr)-1))." and ".$arr[count($arr)-1]);
?>

Try like this:
$array = array('satay','orange','rambutan');
echo "I eat ".join(' and ', array_filter(array_merge(array(join(', ', array_slice($array, 0, -1))), array_slice($array, -1))));
Duplicate question: Implode array with ", " and add "and " before last item

<?php
$arr = array('satay','orange','rambutan');
$lastElement = array_pop($arr);
echo "I eat " . implode(', ',$arr)." and ".$lastElement;
?>
This will result the same :
I eat satay, orange and rambutan

How about this?
function render_array_as_serial_comma($items) {
$items = $variables['items'];
if (count($items) > 1) {
$last = array_pop($items);
return implode(', ', $items) . ' and ' . $last;
}
return array_pop($items);
}
This should do the following:
echo render_array_as_serial_comma(array('a'));
echo render_array_as_serial_comma(array('a', 'b'));
echo render_array_as_serial_comma(array('a', 'b', 'c'));
a
a and b
a, b and c

Related

check the same char in strg and remove and split from underscore in PHP?

Hello I have one string "22A_n22A" and i want to remove the same character from this string and want to split from "_" to two string like 22A and n22A.
i tried it but did not get any solution.
final out put i want like 22A_n22A to (n)22AA
<?php
function conti($str,$case_sensitive = false) {
//if($com1 = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $newval))
if(strcmp($case_sensitive , $case_sensitive) === 0 )
{
$pieces = explode("_", $str);
$str1 = $pieces[0];
$str2 = $pieces[1];
$ary1 = str_split($str1);
$ary2 = str_split($str2);
if (isset($case_sensitive))
{
$ary1 = array_map('strtolower',$ary1);
$ary2 = array_map('strtolower',$ary2);
}
$com = implode('',array_intersect($ary1,$ary2));
$diff = implode('',array_merge(array_diff($ary1, $ary2),array_diff($ary2, $ary1)));
$int = (int) filter_var($com, FILTER_SANITIZE_NUMBER_INT);
$onlystr = preg_replace('/\d/', '', $com);
$newval= '('.$diff.')'.$int.$onlystr.$onlystr;
// $com1 = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $str);
echo '<pre><h1>';
echo 'new value:';
print_r($newval);
echo "<br>";
echo "<br>";
echo "<br>";
echo 'new value:';
print_r($com);
echo "<br>";
echo 'new diff:';
print_r($diff);
echo '</pre>';
return $newval;
}
else {
echo '<pre><h1>';
echo 'oldvalue:';
print_r($str);
echo '</pre>';
return $str;
}
}
echo(conti('71A_n71A'));
// echo(conti('66A_n66A'));
?>
As stated in your comments your requirement is to:
Split the string on _
Pluck the last character from the first chunk of the string and append that to the end of the second string
Wrap the first character of the second chunk of the string in parentheses
For example, 65A_n66A becomes (n)66AA.
You can do this with by performing explode() on the original string, extracting the parts you need and piecing them back together in your desired format:
function format($string) {
list($first, $second) = explode('_', $string);
return sprintf('(%s)%s%s',
$second[0],
substr($second, 1),
$first[strlen($first) - 1]
);
}
This yields:
echo format('22A_n22A'); // (n)22AA
echo format('11A_n22B'); // (n)22BA
echo format('65A_n66A'); // (n)66AA
Hope this helps :)

PHP function to lowercase each character in a string except for the last one

I'm trying to lowercase every character in a string except for the last one that should be in uppercase.
Here is my code:
function caps_caps($var) {
$var = strrev(ucwords(strrev($var)));
echo $var;
}
caps_caps("HeLlo WOrld"); // should returns "hellO worlD"
This is the easy solution of this problem
function caps_caps($var) {
$var = strrev(ucwords(strrev(strtolower($var))));
echo $var;
}
caps_caps("HeLlo WOrld");
Demo
You also need to convert the string to lowercase first.
function caps_caps($var) {
$var = strrev(ucwords(strrev(strtolower($var))));
echo $var;
}
caps_caps("HeLlo WOrld"); // returns "hellO worlD"
function caps_caps($text) {
$value_to_print = '';
$text = strrev(ucwords(strrev($text)));
$words = explode(' ', $text);
foreach($words as $word){
$word = strtolower($word);
$word[strlen($word)-1] = strtoupper($word[strlen($word)-1]);
$value_to_print .= $word . ' ';
}
echo trim($value_to_print);
}
caps_caps("HeLlo WOrld");
You can try this piece of code.
function uclast($s)
{
$lastCharacterUppar = '';
if ( preg_match('/\s/',$s) ){//If string has space
$explode = explode(' ',$s);
for($i=0;$i<count($explode);$i++){
$l=strlen($explode[$i])-1;
$explode[$i] = strtolower($explode[$i]);
$explode[$i][$l] = strtoupper($explode[$i][$l]);
}
$lastCharacterUppar = implode(' ', $explode);
} else { //if string without space
$l=strlen($s)-1;
$s = strtolower($s);
$s[$l] = strtoupper($s[$l]);
$lastCharacterUppar = $s;
}
return $lastCharacterUppar;
}
$str = 'hey you yo';
echo uclast($str);
Try this, you forgot to do foreach, each elements.
function uclast_words($text, $delimiter = " "){
foreach(explode($delimiter, $text) as $value){
$temp[] = strrev(ucfirst(strrev(strtolower($value))));
}
return implode($delimiter, $temp);
}
print_r(uclast_words("hello world", " "));
I hope this is the answer of your question.
Here is a multibyte safe technique that performs the title-casing with one call instead of two. The string reversal and re-reversal is still necessary.
Code: (Demo)
echo strrev(
mb_convert_case(
strrev('HeLlo WOrld'),
MB_CASE_TITLE
)
);
// hellO worlD

PHP Foreach inside variable with equals

I have a variable that equals some simple data as shown below
$var = 'hello names here how are yous?';
what i wish to achieve is have a foreach loop inside the $var but i have tried various ways with just no luck, always throwing errors.
Below is somewhat what i what to do.
$var = 'hello '.foreach($datas as $data) { echo $data }.' how are yous?';
echo $var;
which would output - hello Mike Daniel Steve how are yous?
any help appreciated.
======EDIT========
im trying to write to file the looped contents with below code.
$datas = 'Name, Name2, Name4';
$var = ''.foreach($datas as $data) { echo $data }.'
$default_file = 'media/default.php';
$default_file_handle = fopen($default_file, 'w') or die('Cannot open file: '.$default_file);
$default_data = '
'.$var.'//each value to be a new line
Name2 //example
Name4 //example
etc
';
fwrite($default_file_handle, $default_data);
so basically im write to file each value in the loop to a new line. I can write just normal content but getting a loop in their im struggling with
$var = 'hello';
foreach($datas as $data) {
$var .= ' '.$data.' ';
}
$var .= ' how are you?';
echo $var;
that should do it
$arr = array("Mike", "John");
echo "Hello " . implode(" ", $arr) . ", how are you?";
implode is your friend. Implode joins array elements together into one single string. The separator between each array element is the first parameter - in this case a blank.
You can use implode:
$var = 'hello '.implode(' ', $datas) .' how are yous?';
echo $var;
To achieve this you either have to insert the foreach loop like this:
echo "hello ";
foreach($datas as $data) {
echo $data;
}
echo " how are you?";
or you can use an extra variable and the implode method:
$dataString = implode(" ", $datas);
echo "hello " . $dataString . " how are you?";
You can do this following way.
<?php
$data = array('Mike Daniel','john doe');
foreach ($data as $value) {
$result = 'hello '. $value. ' how are you?'. '</br>';
echo $result;
}

PHP to form string like "A, B, C, and D" from array values

Given the following array:
Array
(
[143] => Car #1
[144] => Car #2
[145] => Car #3
)
I am currently using this
implode(', ', array_values($car_names))
to generate a string like
Car #1, Car #2, Car #3
I would like to actually get something like
Car #1, Car #2 and Car #3
The idea would be to insert " and " between the two last elements of the array.
If the array happens to contain two key/value pairs (eg, user has 2 cars), there would be no commas.
Car #1 and Car #2
And if the array contains one key/value (eg, user has 1 car)
Car #1
Any suggestion how to get this done? I tried using array_splice but I'm not sure that's the way to go (ie, inserting a new element into the array).
Thanks for helping!
$last = array_pop($car_names);
echo implode(', ', $car_names) . ' AND ' . $last;
I think you probably want something like this, using array_pop to get the last element off the end of the array. You can then implode the rest of the array, and add the last element in a custom fashion:
$last_value = array_pop($car_names);
$output = implode(', ', array_values($car_names));
$output .= ($output ? ' and ' : '') . $last_value;
Edit: added conditional to check if the array had only one element.
A preg_replace can look for the last command just just swap it to an and
$yourString = preg_replace( "/, ([\w#]*)$/", "and \1", $yourString );
This solution is a bit longer, but tested for all array sizes and it is a complete solution. Also, it doesn't modify the array like the above answers and is separated into a function.
function arrayToString($arr) {
$count = count($arr);
if ($count <= 2) {
return implode(' and ', $arr);
}
$result = '';
$i = 0;
foreach ($arr as $item) {
if ($i) $result .= ($i == $count - 1) ? ' and ' : ', ';
$result .= $item;
$i++;
}
return $result;
}
Compacted version with ugly formatting and ignoring good practices like initializing variables:
function arrayToString($arr) {
if (count($arr) <= 2) return implode(' and ', $arr);
foreach ($arr as $item) {
if ($i) $result .= ($i == count($arr) - 1) ? ' and ' : ', ';
$result .= $item; $i++;
}
return $result;
}
I'm not sure there's a built in function for this, but something like this should work.
$last = $car_names[count($car_names)-1];
$implodedString = implode(', ', array_values($car_names))
$implodedString = str_replace(", $last", "and $last", $implodedString);
That's an example with the functions named in my comment above:
strrpos() - Find the position of the last occurrence of a substring in a string
substr() - Return part of a string
and the code:
$text = implode(', ', array_values($car_names));
$last = strrpos($text, ',');
if ($last) $text = substr($text, 0, $last-1) . ' AND ' . substr($text, $last+1);
echo $text;
There are a number of ways you could do this. Here's another.
<?php
$cars = array('Car #1', 'Car #2', 'Car #3', 'Car #4');
$car = array('Car #1');
$twocars = array('Car #1', 'Car #2');
function arrayToText($arr) {
switch (count($arr)) {
case 1:
return $arr[0];
break;
case 2:
return implode($arr, ' and ');
break;
default:
$last = array_pop($arr);
return implode($arr, ', ') . ' and ' . $last;
break;
}
}
echo '<p>' . arrayToText($cars) . "</p>\n";
echo '<p>' . arrayToText($twocars) . "</p>\n";
echo '<p>' . arrayToText($car) . "</p>\n";
Output
<p>Car #1, Car #2, Car #3 and Array</p>
<p>Car #1 and Car #2</p>
<p>Car #1</p>

finding last entry of foreach() loop, implode not working

I loop through my array to print the articles names:
<?php
if ($articles) {
foreach($articles as $article) {
echo $article->name.", ";
} // end foreach article
} // end if has articles
?>
This will obviously produce something like
Apple, Banana, Mango,
But I am looking for:
Apple, Banana, Mango
I tried some implode statement like this:
<?php
if ($articles) {
foreach($articles as $article) {
echo implode(", ", $article->name);
} // end foreach article
} // end if has articles
?>
or
<?php
if ($articles) {
echo implode(", ", $articles->article->name);
} // end if has articles
?>
None of these are working for me. How can do it right? Thanks for hints!
You can use foreach to add the article names to an array, then implode() that array of names.
<?php
if ($articles) {
$article_names = array();
foreach($articles as $article) {
$article_names[] = $article->name;
} // end foreach article
echo implode(', ', $article_names);
} // end if has articles
?>
it's much more easy to check for your first loop-iteration, wrte the comma before your text and leave this comma aout on the first iteration:
<?php
if ($articles) {
$firstiteration = true:
foreach($articles as $article) {
if(!$firstiteration){
echo ", ";
}
$firstiteration = false;
echo $article->name;
} // end foreach article
} // end if has articles
?>
another (more beautiful in my optionion) possibility would be to override the _toSting()-method of your article-class:
...
function __toString(){
return $this->name;
}
...
and simply echo implode(", ",$articles)
It is better way to do what you want:
<?php
$string = '';
if ($articles) {
foreach($articles as $article) {
$string .= $article->name.", ";
}
}
$string = substr($string, 0, -2);
echo $string;
?>
PHP has a lot of good array functions, and this screams for one of them.
$namesArray = array_map(function($x){return $x->name;}, $articles);
$string = implode(',' $namesArray);
OR
$first = true;
array_walk(function($x) use (&$first)
{
if(!$first) {echo ', ';} else{$first = false;}
echo $x->name;
}, $articles);
I really like the above response with the __toString function also, but I wanted to show these array functions because i think they are often underused in favor or unnecessary foreach loops.
You can remove last comma and space by using trim function. It is the easiest way..
<?php
if ($articles) {
foreach($articles as $article) {
echo trim(implode(", ", $article->name), ', ');
}
}
?>

Categories