PHP array split into custom sentence? - php

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;

Related

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

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;

How can I put '-' between words in this code php?

Below code will echo like this
('nice apple'),(' nice yellow banana'),(' good berry ')
what I need to do is that I need them to be like this
('nice-apple'),(' nice-yellow-banana'),(' good-berry ')
The challenge is that I could not touch $str, and then I need to use '-' to connect words if there is space between them, If use str_replace space, it will be something like ----nice-apple-. how can I achieve something like this ('nice-apple'), appreciate.
<?php
$str="nice apple,
nice yellow banana,
good berry
 ";
echo $str = "('" . implode("'),('", explode(',', $str)) . "')";
?>
Try str_replace
$str="nice apple,
nice yellow banana,
good berry
";
$str = array_map(function($dr){ return preg_replace('/\s+/', '-', trim($dr));},explode(',',$str));
$str = implode(',',$str);
echo $str = "('" . implode("'),('", explode(',', $str)) . "')";
Output:
('nice-apple'),('nice-yellow-banana'),('good-berry')
Its bit tricky. Try with -
$str="('nice apple'),(' nice yellow banana'),(' good berry ')";
$v = explode(',', $str); // generate an array by exploding the string by `,`
foreach($v as $key => $val) {
$temp = trim(str_replace(["(", "'", ")"], "", $val)); //remove the brackets and trim the string
$v[$key] = "('".str_replace(" ", "-", $temp)."')"; // place the `-`s
}
$new = implode(",", $v); // implode them again
var_dump($new);
you need to get rid of the new lines first then it'll work.
<?php
$str="nice apple,
nice yellow banana,
good berry
";
$arr = explode(',', str_replace([ "\r\n", "\n" ], "", $str));
$arrCount = sizeOf($arr);
for($x = 0; $x < $arrCount; $x++) {
while (preg_match('/(\w)\s(\w)/', $arr[$x])) {
$arr[$x] = preg_replace('/(\w)\s(\w)/', '$1-$2', $arr[$x]);
}
}
echo $str = "('" . implode("'),('", $arr) . "')";
?>
('nice-apple'),(' nice-yellow-banana'),(' good-berry ')

remove word from string by position from input

EXAMPLE:
input = 2
text = aa bb cc
Will become: aa cc
The input for position is $_POST['position']
i have
$words = explode(" ", $_POST['string']);
for ($i=0; $i<count($words); $i++){
echo $words[$i] . " ";
}
$to_remove = 2;
$text = "aa bb cc";
$words = explode(' ', $text);
if(isset($words[$to_remove -1])) unset($words[$to_remove -1]);
$text = implode(' ', $words);
Pulling out the big guns REGEX !!!
$string = 'aa bb cc dd';
$input = 2;
$regex = $input - 1;
echo preg_replace('#^((?:\S+\s+){'.$regex.'})(\S+\s*)#', '$1', $string);
Output: aa cc dd
Foreach loops tend to make it a little easier to understand (IMO). Looks cleaner too.
$pos = 2;
$sentence = explode(" ", $_POST['string']);
foreach ($sentence as $index => $word) {
if ($index != $pos - 1) {
$result .= $word . ' ';
}
}
echo $result;
This sounds like a homework question. I'll take a stab at it though:
Code:
<?php
$string = trim($_POST['string']);
$parts = explode(" ", string);
$newString = "";
$position = intval($_POST['position']);
for($a = 0; $a < count($parts); $a++) {
if($a != $position) { // or $a != ($position - 1) depending on if you passed in zero based position
$newString = $newString . $parts[$a] . " ";
}
}
$newString = trim($newString);
echo "Old String: " . $string . "<br />";
echo "New String: " . $newString;
?>
Output:
Old String: aa bb cc
New String: aa cc
$input = 2;
$words = explode(" ", $_POST['string']);
unset($words[$input-1]);
$words = implode(" ", $words);
echo $words;

format explode data after first piece with foreach

What I have is this array:
$l = "apple,orange,tomato,banana,carrot,celery";
What i'm trying to do is something along these lines:
apple OR orange OR tomato OR banana OR carrot OR celery
I've gotten this far:
$l = explode(",", $l);
if (count($l) > 1){
foreach ($l as $s){
echo " OR " . $s;
}
}
Doing it this way puts OR in front of all the pieces of the array:
OR apple OR orange OR tomato OR banana OR carrot OR celery
What would be the proper way to count the first piece, then append to all the additional pieces?
try this:
$array = explode(",", $l);
echo implode(" OR ", $array);
Or in one liner:
echo implode(" OR ", explode(",", $l));
Use str_replace:
$string = 'oranges,apples,pineapple';
echo str_replace(',', ' OR ', $string);
// Outputs: oranges OR apples OR pineapple
one line skill
$array = implode (' OR ', explode (',', $array));
You may try with this :)
echo preg_replace('/,/', " OR ", "apple,orange,tomato,banana,carrot,celery");
or in case you want to treat the information :
$pieces = explode (',', $array);
$result = '';
$i = 0;
foreach ($pieces as $p) {
$i++;
if ($p === 'banana') // in case you hate banana
continue;
$result .= $p;
if ($i != count($pieces))
$result .= ' OR ';
}

PHP format split number into separate html tags

How would I go and split number 12345 into something like this with PHP:
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
echo preg_replace('((.))', "<span>$1</span>\n", '12345');
Try with:
$input = 12345;
foreach ( str_split($input) as $char ) {
echo '<span>' . $char . '</span>';
}
With str_split()
<?php
$str="12345";
$str = str_split($str);
foreach ($str as $letter){
echo '<span>'.$letter.'</span>'.PHP_EOL;
}
?>
$str = '12345';
$arr = str_split($str);
foreach ($arr as $char) {
echo '<span>' . $char . '</span>';
}
var arr = explode('', "12345");
Then iterate throgh it with foreach and echo (or do whatever you want with) the tags.
If the input string will be large, something like this will be more memory-friendly and possibly faster because it streams instead of breaking it apart first.
$string = "12345";
for ($i = 0, $j = strlen($string); $i < $j; $i++) {
echo "<span>" . $string{$i} . "</span>\n";
}

Categories