How to output repeat strings with looping and explode method only - php

e.g. "I think I got a long way to go to market."
In this case, I want to output
I 2
think 1
got 1
a 1
long 1
way 1
to 2
go 1
market 1
Code:
<?php
$tmp = explode (" ", $text);
echo "
My Words
Repetition
";
foreach ($tmp as $a)
{
echo "" $a."" ;
echo "" ;
}
echo ""
?>

You can try with
$text = "I think I got a long way to go to market.";
$tmp = explode (" ", $text);
foreach($tmp as $a){
$result[$a] += 1;
}
foreach($result as $value => $occurrences){
echo "$value $occurrences\n";
}

Related

Php array display array element 4 per line [duplicate]

This question already has answers here:
Selecting multiple array elements
(3 answers)
Closed 1 year ago.
Hey GUys Im beginner to php programming here here i have 15 element in array . i want to display first 4 array element in first line and then second 4 array of element in nextline . i dont know how to achive it here is my code help me on this. thanks in advance
<?php
$arry=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
echo $nr_elm = count($arry); // gets number of elements in $arry
$nr_col = 4; // Sets the number of text Per Line
// If the array has elements
if ($nr_elm > 0)
{
// Traverse the array with FOR
for($i=0; $i<$nr_elm; $i++)
{
echo $textInLine= $arry[$i]. ' | ';
// If the number of columns is completed for a line (rest of division of ($i + 1) to $nr_col is 0)
// Closes the current line, and begins another line
$col_to_add = ($i+1) % $nr_col;
if($col_to_add == 0) { $textInLine .= '/n'; }
}
}
echo $textInLine;
?>
Use array_chunk for this:
$array = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$size = 4;
foreach (array_chunk($array, $size) as $chunk) {
echo implode(' ', $chunk) . PHP_EOL;
}
Another solution without using array_chunk is using modulo:
$array = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$size = 4;
$counter = 0;
foreach ($array as $character) {
echo $character;
// echo new line after every 4th character, a space after the others
echo (++$counter % $size === 0) ? PHP_EOL : ' ';
}
Chunk the array and implode the items in the chunk.
$arry=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$chunks = array_chunk($array, 4);
foreach($chunks as $chunk){
echo implode(" ", $chunk) . "</br>\n";
}
Array_chunk splits the array in to pieces of the size you define.
The resulting array is multidimensional with the items in the subarray.
Implode takes the items in the subarray and adds the delimiter (" ") in between each item and makes it a string.
Use array_chunk, it will Split an array into chunks
<?php
$arry=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$arr = array_chunk($arry, 4, true);
foreach($arr as $value) {
echo implode(' ', $value) . PHP_EOL ;
}
?>
I don't know if the "15" is intentional, but if you want to remove it just remove the "echo".
I also recommend to use empty() to verify if your array is empty or not, just like this :
if (!empty($arry)) { //Code }
(notice the "!")
Now, for your main question what I would do is using a variable which increments up to 4, then you insert a line break with echo <br>; and reset the variable to 0.
The code should look something like this :
$c = 0;
for($i=0; $i<$nr_elm; $i++)
{
echo $arry[$i];
$c ++;
if ($c >= 4) {
echo "<br>";
$c = 0;
}
}
I hope this helped you

PHP New Line after n commas

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>";
}
?>

loop in php function foreach

I try to get the result
danny love to eat orange and banana and grapes
Is it possible to get it through the function foreach
my Sample Code
$var = array (" orange "," banana "," grapes ");
echo 'danny love to eat ';
//NOT THIS METHOD
// echo $var [0];
// echo ("and");
// echo $var [1];
// echo ("and");
// echo $var [2];
//Through this method
foreach ($var as $fruit) {
echo $fruit ;
echo ("and");
}
The result I get if i use foreach
danny love to eat orange and banana and grapes and
What's wrong ? :(
You're echoing 'and' one too many times. You don't want to echo 'and' if you're on the last element.
Try this instead.
$var = array (" orange "," banana "," grapes ");
echo 'danny love to eat ' .implode('and',$var);
#bassxzero's answer is a great (In fact, I would recommend doing it that way over this way), but I wanted to show another way you could do this if you wanted to use a foreach loop still if you wanted to.
$var = array ("orange","banana","grapes");
$string = 'danny love to eat ';
//Through this method
foreach ($var as $fruit) {
$string .= $fruit. " and ";
}
$string = substr($string, 0, -5);
echo $string;
In my code, we are building a string that contains all the words that you want seperated by " and ". Then as soon as the loop is done, we use substr() to remove the very last " and " so that $string equals the string you were expecting.
Another solution could be
$var = array (" orange "," banana "," grapes ");
$str = 'danny love to eat ';
$total = count($var); // counts your aray
foreach ($var as $fruit) {
$total--; // decrements $total value
$str .= $total < 1 ? $fruit : $fruit.' and '; //if $total is reduced to 0 your loop is on the last repeat, so dont print 'and' anymore
}
echo $str;
Anyway implode way is the most elegant here.

PHP extract 1 or more value from array_filter

Sorry this must me simple but I am terrible on arrays.
I need to extract $d1,$d2,$d3,$d4,$d5,$d6 from
array_filter($d1,$d2,$d3,$d4,$d5,$d6)
Example
$pieces = array_filter([$d1,$d2,$d3,$d4,$d5,$d6]);
if(count(array_filter($pieces)) == 2){ echo $d1.' '.$d2 }
Thank you!
You need the array in a variable:
(not sure on your context but is 'array_filter' needed at all?
$myArray = array($d1, $d2, $d3, $d4, $d5, $d6);
Then when echoing $d1.' '.$d2 for example:
echo $myArray[0] . ' ' . $myArray[1];
Update
So to more accurately answer your question, I'm assuming you want to echo all array items, use a for loop:
$output;
for ($i = 0; $i< count($pieces); $i++){
output .= $pieces[$i] . ' ';
}
echo $output;
you are on right track. Try below soltuion:
$array = array('test1','test2','','test4','','','','testx');
//remove empty values
$filterd_array = array_filter($array);
//implode with space and print
echo implode(' ', $filterd_array);
output:
test1 test2 test4 testx

Foreach loop, but for first key do something else

Sorry if this is confusing. It's tough for me to put into words having beginner knowledge of PHP.
I'm using the following foreach loop:
foreach ($_POST['technologies'] as $technologies){
echo ", " . $technologies;
}
Which produces:
, First, Second, Third
What I want:
First, Second, Third
All I need is for the loop to skip the echo ", " for the first key. How can I accomplish that?
You can pull out the indices of each array item using => and not print a comma for the first item:
foreach ($_POST['technologies'] as $i => $technologies) {
if ($i > 0) {
echo ", ";
}
echo $technologies;
}
Or, even easier, you can use implode($glue, $pieces), which "returns a string containing a string representation of all the array elements in the same order, with the glue string between each element":
echo implode(", ", $_POST['technologies']);
For general case of doing something in every but first iteration of foreach loop:
$first = true;
foreach ($_POST['technologies'] as $technologies){
if(!$first) {
echo ", ";
} else {
$first = false;
}
echo $technologies;
}
but implode() is best way to deal with this specific problem of yours:
echo implode(", ", $_POST['technologies']);
You need some kind of a flag:
$i = 1;
foreach ($_POST['technologies'] as $technologies){
if($i > 1){
echo ", " . $technologies;
} else {
echo $technologies;
}
$i++;
}
Adding an answer that deals with all types of arrays using whatever the first key of the array is:
# get the first key in array using the current iteration of array_keys (a.k.a first)
$firstKey = current(array_keys($array));
foreach ($array as $key => $value)
{
# if current $key !== $firstKey, prepend the ,
echo ($key !== $firstKey ? ', ' : ''). $value;
}
demo
Why don't you simply use PHP builtin function implode() to do this more easily and with less code?
Like this:
<?php
$a = ["first","second","third"];
echo implode($a, ", ");
So as per your case, simply do this:
echo implode($_POST['technologies'], ", ");

Categories