How to add a variable with each array element in php? [duplicate] - php

This question already has answers here:
Php: Concatenate string into all array items
(6 answers)
Implode an array with ", " and add "and " before the last item
(16 answers)
Closed 8 months ago.
I want to add variables with each array item but I do not have clue what to do? Here is my code. Can anyone help me, please? Thanks
$str = "Ice Cream has";
$optional= "flavor";
$items = array("vanilla","chocolate","mango");
$itemsCount = count($items);
$sentence = '';
if ($itemsCount == 1) {
$sentence = $items[0] . '.';
} else {
$partial = array_slice($items, 0, $itemsCount-1);
$sentence = implode(', ', $partial).' '. $optional. ' and ' . $items[$itemsCount-1];
}
return $str.': '.$sentence.'.';
I want an output should be:
"Ice Cream has: vanilla flavor, chocolate flavor and mango flavor."
But I am getting output:
"Ice Cream has: vanilla, chocolate flavor and mango ."

You need to concatenate $optional to all elements of the array, not just the result of implode(). You can use array_map() to create a new array with $optional added to each element.
$str = "Ice Cream has";
$optional= "flavor";
$items = array("vanilla","chocolate","mango");
$items1 = array_map(function($x) use ($optional) { return "$x $optional"; }, $items);
$itemsCount = count($items1);
$sentence = '';
if ($itemsCount == 1) {
$sentence = $items[0] . '.';
} else {
$partial = array_slice($items1, 0, $itemsCount-1);
$sentence = implode(', ', $partial). ' and ' . $items1[$itemsCount-1];
}
return $str.': '.$sentence.'.';

$str = "Ice Cream has: ";
$optional= "flavor";
$items = array("vanilla","chocolate","mango");
$count = count($items);
$c=0;
if ($count == 1) {
$str .= $items[0] . ' '.$optional.'.';
} else {
foreach( $items as $item){
$c++;
if( $c == $count){
$str = $str.' and '.$item.' '.$optional.'.';
}else if($c == $count-1){
$str = $str.$item.' '.$optional.'';
}else{
$str = $str.$item.' '.$optional.', ';
}
}
}
return $str;

Related

PHP array split into custom sentence?

I have a PHP array and I want to split it into a custom sentence.
$array = array('apple','blue','red','green');
I want the output below:
apple
apple blue
apple blue red
apple blue red green
You could try this simple solution
$array = array('apple','blue','red','green');
$sentence = "";
foreach($array as $key) {
if($sentence === ""){
$sentence = $key;
}
else{
$sentence = $sentence." ".$key;
}
echo $sentence;
echo "</br>";
}
Pretty simple lightweight solution
$array = array('apple','blue','red','green');
$str = '';
foreach($array as $item) {
$str = $str . ' ' . $item;
echo(ltrim($str) . '<br>');
}
Use for-loop with array_slice to Extract a slice of the array each time, And use implode(glue, pieces) to join the values of the array with a space.
$array = array('apple','blue','red','green');
for ($i=1; $i <= count($array) ; $i++) {
echo implode(' ', array_slice($array, 0, $i))."</br>";
}
Prints:
apple
apple blue
apple blue red
apple blue red green
This is very simple
$array = array('apple','blue','red','green');
$new = "";
for($i=0; $i<sizeof($array); $i++) {
for($j=0; $j<=$i; $j++){
$new .= $array[$j]." ";
}
$new .= "<br>";
}
echo $new;

How to reformat a string of words with commas/ampersands in PHP

I am trying to write some PHP code that will separate words when the are two with "&" and a comma when they are three and the last two with "&"
Something like this
$string = "stack over flow";
Print on screen like this "stack, over & flow";
Hope you noticed the comma and the ampersand.
Then when they are two words
$string = "stack overflow";
print like this echo "stack & overflow";
Here is my code I have been trying, but I am not getting it right:
$string = '1,2';
$list = explode(',',$string);
foreach($list as $row) {
if($list = 2) {
echo ''.$row.' &';
}
}
This should take into account the possibilities of one or more words. If there is more than one word, just remove the last word (using array_pop()) and implode() with , the remaining words.
If there is only 1 word, the result is the same as the original string...
$string = "stack over";
$list = explode(" ", $string);
if ( count($list) > 1 ) {
$last = array_pop($list);
$result = implode(", ", $list) . " & {$last}";
}
else {
$result = $string;
}
To add anchor tags to each word...
$list = explode(" ", $string);
$aTag = '<a href="#">';
if ( count($list) > 1 ) {
$last = array_pop($list);
$result = $aTag.
implode("</a>, {$aTag}", $list) . "</a> & {$aTag}{$last}</a>";
}
else {
$result = $aTag.$string."</a>";
}
echo $result;
thanks Nigel Ren.. you code was really helpfully
but their a correction i made.Here
$string = "stack over flow";
$list = explode(" ", $string);
$aTag = '<a href="#">';
if ( count($list) > 1 ) {
$last = array_pop($list);
$result = $aTag.
implode('</a>, '.$aTag.'', $list) . "</a> & {$aTag}{$last}</a>";
}
else {
$result = $aTag.$string."</a>";
}
echo $result;
thanks

Combine two arrays into a string

I need to create a new array called ar1 with the items: [Dublin, Budapest, Copenhagen] and ar2 with [Ireland, Hungary, Denmark] after than answer with a string containing each country from the countries-array followed by the corresponding capital. Use the format "country = capital,
* country = capital..."
Check code below but i know that is another way to doing that ex. For loop but can someone explain me how?
$ar1 = ["Dublin", "Budapest", "Copenhagen"];
$ar2 = ["Ireland", "Hungary", "Denmark"];
$ANSWER = $ar2[0] . " = " . $ar1[0] . ", " . $ar2[1] . " = " . $ar1[1]. ", " . $ar2[2] . " = " . $ar1[2];
You should use a foreach and the key.
$ar1 = ["Dublin", "Budapest", "Copenhagen"];
$ar2 = ["Ireland", "Hungary", "Denmark"];
$ANSWER = '';
foreach($ar1 as $key => $capital) {
$ANSWER .= $ar2[$key] . ' = ' . $capital . ', ';
}
echo rtrim($ANSWER, ', ');
... and then rtrim to remove the last ,.
https://3v4l.org/f8PJN
Another way to do it using array_combine()
<?php
$ar1 = ["Dublin", "Budapest", "Copenhagen"];
$ar2 = ["Ireland", "Hungary", "Denmark"];
$result = array_combine($ar2,$ar1);
$ANSWER = '';
$i = 0;
$comma = ', ';
$len = count($result);
foreach($result as $country => $capital) {
if ($i == $len - 1){
$comma='';
}
$ANSWER .= $country . ' = ' . $capital.$comma;
$i++;
}
echo $ANSWER;
DEMO: https://3v4l.org/WGtJ3
Using array_map()
$ar1 = ["Dublin", "Budapest", "Copenhagen"];
$ar2 = ["Ireland", "Hungary", "Denmark"];
$input = array_combine($ar2,$ar1);
$output = implode(', ', array_map(
function ($v, $k) { return sprintf("%s=%s", $k, $v); },
$input,
array_keys($input)
));
echo $output;
DEMO: https://3v4l.org/qps1G
More fast and simple way:
$countries=["Ireland", "Hungary", "Denmark"];
$capitals=["Dublin", "Budapest", "Copenhagen"];
$string=implode(',',array_map(function($country,$capital){ return "$country=$capital";},$countries,$capitals));
var_dump($string);
output:
string(50) "Ireland=Dublin,Hungary=Budapest,Denmark=Copenhagen"
If you've got two related lists in separate variables, it's often easier to transpose them into a single structure first. In PHP, you can do this like so:
$transposed = array_map(null, $ar1, $ar2);
Once they're combined, it's a lot more simple to generate the required output:
echo implode(', ', array_map(function($row) {
return "{$row[1]} = {$row[0]}";
}, $transposed));
Ireland = Dublin, Hungary = Budapest, Denmark = Copenhagen
See https://3v4l.org/LfvIY

Echo all values in php array as a sentence

Is it possible to display an array as a sentence? So between each of the values there would be ", " except before the last value there would be " and ".
I have taken this little piece of code to use within an example:
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
This works great for three values but I need it to work for between 1 and 15 values.
Thanks
$carsCount = count($cars);
if ($carsCount == 1) {
$sentence = $cars[0] . '.';
} else {
$partial = array_slice($cars, 0, $carsCount-1);
$sentence = implode(', ', $partial) . ' and ' . $cars[$carsCount-1];
}
echo $sentence;
$array = array("Volvo", "BMW", "Toyota");
$sentence = '';
foreach($array as $k => $v) {
if (count($array) == 1) {
$sentence = $v;
break;
}
else if ($k == count($array)-1) {
$sentence .= 'and ' . $v;
}
else {
$sentence .= $v . ', ';
}
}
echo $sentence;
Above returns the following: Volvo, BMW, and Toyota
There is another way [shorter], [faster].
$cars = array("Volvo", "BMW", "Toyota", "Fiat");
if (count($cars) > 1) {
$lastVal = array_pop($cars);
echo implode(",", $cars)." and ".$lastVal;
} else {
echo $cars[0];
}

How to wrap words of string every 1000 characters in php

i have some big string, and some array of words that must be replaced with some changes, like wrapping in link. First issue is wrap whole words or combinations words. And the second issue is do previous step minimum every 1000 characters.
$string="lalala word lalala blah, blah lalala combination of words lalala lalala...";
$patterns=array('word','combination of words');
$replacements=array('word','combination of words');
For an example, what i must to do with snippet before?
It sounds to me like you're looking for wordwrap(). You can then use preg_replace_callback() to apply it to your search patterns and make the replacements:
foreach ($patterns as $pattern) {
$regex = '/' . preg_quote($pattern, '/') . '/';
$string = preg_replace_callback($regex, function($match) {
return '<a href="#">'
. wordwrap(htmlspecialchars($match), 1000, '<br />')
. '</a>';
}, $string);
}
SOLUTION:
<?php
function set_keys_by_words($content, $key, $words,$before,$after) {
$positions = array();
$string = '';
for ($i = 0; $i < count($words); $i++) {
$string = preg_replace('/\b' . $words[$i] . '\b/ui', $key . $words[$i], $content);
$position = mb_strpos($string, $key);
if ($position != '') {
$positions[(int) $position] = $words[$i];
}
}
ksort($positions);
$word = '';
$number = '';
$i = 0;
foreach ($positions as $k => $v) {
$i++;
if ($i == 1) {
$number = $k;
$word = $v;
}
}
if ((int) $number) {
$word_len = strlen($word);
$part_after = preg_replace('/\b' . $word . '\b/ui', $before . $word . $after, mb_substr($content, 0, $number + $word_len));
echo $part_after . mb_substr($content, $number + $word_len, 1000);
$content = mb_substr($content, $number + $word_len + 1000);
if ($content != '') {
set_keys_by_words($content, $key, $words);
}
} else if ($number == '' && $content != '') {
echo $content;
}
}
?>

Categories