how to order in while loop? - php

I want to get the count of characters from the following words in the string. For example, if my input is I am John then the output must be like this:
9 // count of 'I am John'
4 // count of 'I am'
1 // count of 'I'
I use the code like this in PHP for this process:
$string = 'I am John';
$words = explode(' ',$string);
$count_words = count($words);
$i =0;
while ($i<$count_words){
if($i==0) {
$words_length[$i] = strlen($words[$i]);
} else {
$words_length[$i] = strlen($words[$i])+1+$words_length[$i-1];
}
echo $words_length[$i]."<br>";
$i++;
}
But it return the output like this:
1
4
9
Why ? Where is my error ? How can I change the ordering ? What does my code must be like ?
Thanks in advance!

If you simply want to have the output in reverse order use array_reverse:
print_r(array_reverse($words_length));

Your problem is that you're looping through the words left to right. You can't output the full length right to left, because each one depends on the words to it's left.
You could take the echo out of the loop, and print the values after all have been calculated.
$string = 'I am John';
$words = explode(' ',$string);
$count_words = count($words);
$i =0;
while ($i<$count_words){
if($i==0) {
$words_length[$i] = strlen($words[$i]);
} else {
$words_length[$i] = strlen($words[$i])+1+$words_length[$i-1];
}
$i++;
}
print implode('<br />', array_reverse($words_length));

The quickest fix is to add print_r(array_reverse($words_length)); after the loop

You may use foreach and array_reverse to get the array values:
foreach(array_reverse($words_length) as $val){
echo $val;
}

Related

Count how many numbers and letters in the variable using PHP

I'd like to count how many numbers and letters are in the variable using PHP. Below if my code:
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
echo 'END UNIT: '.substr_count($lot_num, 'E').'<br />';
the code will count how many letter E are there in my lot_num variable but i would also like to count how many numbers are in the variable. Supposed, E1 and E18 should not be included when counting numbers.
I hope you can help me guys.
Try this: explode on , to get array that can be counted.
https://3v4l.org/r6OKl
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$ecount = substr_count($lot_num, 'E');
$totcount = count(explode(",", $lot_num));
echo 'END UNIT: '.$ecount;
Echo "\ntotal count: ". $totcount;
Echo "\nother count: ". Intval($totcount-$ecount);
No loops and no regex makes it a simple and quick solution.
You could always turn it into an array and use a loop:
$lot_num = explode(',',strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$count = 0;
for ($i=0;$i<count($lot_num);$i++) {
if (is_int($lot_num[$i])) { //detects all numbers
$count++;
}
}
echo $count;
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$array = explode(',', $lot_num);
$data=array();
foreach($array as $k=>$val){
if(is_numeric($val )){
$data['number'][] = $val;
}else{
$data['string'][] = $val;
}
}
echo count($data['number']);
echo count($data['string']);
you can use is_numeric() and
if (!preg_match("/^[a-zA-Z]$/", $param)) {
// throw an Exception...
}
inside a loop
Id use preg_match
preg_match('/\b([0-9]+)\b/', $lot_num, $matches );
And matches would be like this.
$mathes[1][1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18]
So you would
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$total = 0;
if( preg_match('/\b([0-9]+)\b/', $lot_num, $matches )){
$total = count( $mathes[1] );
}
You can see how the Regx works here https://regex101.com/r/17psAQ/1
1,first u have to seperate the string and stored into array
2,then u can easily count the value of integers
<?php
$lot_num =explode(',',strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18'));//seperate string by ","
$arr_count=count($lot_num);
for($i=0;$i<$arr_count;$i++)
{
$get_num[]=$lot_num[$i];//saving seperated string value into array
}
$count=0;
for($j=0;$j<count($get_num);$j++)
{
if(is_numeric($get_num[$j]))//chect whether the value is integer or not
{
$count++;
}
}
echo $count;

how to display a string pattern using php loops

my question is how to display string as a pattern using php loops like, if the string is computer,on first iteration it will display "c" and then second iteration it will display like "co" and so on.My following code given below.please give a solution.
<?php
$array = "computer";
$count = strlen($array);
for($i=0;$i<=$count;$i++)
{
echo $array[$i]."<br>";
}
?>
output will print like this
c
co
com
comp
compu
$array = "computer";
$count = strlen($array);
for($i=0;$i<=$count;$i++)
{
echo substr($array,0,$i+1)."<br>";
}
$array = "computer";
$count = strlen($array)-1;
$out='';
for($i=0;$i<=$count;$i++)
{
$out .= $array[$i];
echo $out."<br>";
}
Have a nice day :-)
You can use substr($array, 0, $i + 1) instead of $array[$i]. Visit to: PHP: substr for more information.

PHP Error - Notice: Array to string conversion on imploding an array

I'm trying to write a function that would take the $s parameter and split it into letters thus creating an array of the letters of $s.
$n is the letter counter, so it would loop up to 10 letters and return EricEricEr.
The first issue: I understand I'm creating an array inside an array, and since I would like to receive the string of the inner array, I would need to implode it twice.
The Second issue: I'm unable to print the 10 first letters, only the word 10 times (i.e. EricEricEricEric...10 times).
Expected Result: I would like the for loop i to go over the letters, and when reaching $n and print all the letters with no glue, just consecutively, receiving the result of this specific example function params as: EricEricEr.
function letterCounter($s, $n){
for ($i = 0; $i<=$n; $i++){
$split [] = str_split($s);
}
$imploded = implode($split);
return $imploded;
}
$result = letterCounter('Eric', 10);
echo '<pre>';
print_r($result);
echo '</pre>';
This will do but you can improve the code
function letterCounter($s, $n)
{
$split = str_split($s); //array of splitted $s into letters
$count=0;
$str = "";
while($count<$n){
foreach($split as $char){
if($count>=$n)
break;
$str.= $char;
$count++;
}
}
return $str;
}
$result = letterCounter('Eric', 10);
echo '<pre>';
print_r($result);
echo '</pre>';
Not sure if I got you right here, but PHP got everything you need:
$string = "Eric";
str_pad($string, 10, $string);
"EricEricEr"

PHP : How to avoid any white spaces or empty string in an array

I want to avoid any empty string in an array or any kind of white space. I'm using the following code:
<?php
$str="category 1
category 2
category 3
category 4
";
$var = nl2br($str);
echo $var."<br>";
$arr = explode("\n", $var);
var_dump($arr); echo "<br>";
for($i = 0; $i < count($arr); $i++) {
if(($arr[$i]) != '')
{
echo $arr[$i]."</br>";
}
}
?>
How can I remove the white space or empty string like the 2,3,5 index in the array which don't have needed string.
$array = array_filter(array_map('trim',$array));
Removes all empty values and removes everywhere spaces before and after content!
Your code was pretty much correct, but as was pointed out, your nl2br was adding a <br> to the end of each line and thus making this a harder process than it should have been.
$str="category 1
category 2
category 3
category 4
";
$arr = explode("\n", $str);
var_dump($arr); echo "<br>";
for($i = 0; $i < count($arr); $i++){
if(($arr[$i]) != '')
{
echo $arr[$i]."</br>";
}
}
I used your old code and just removed the nl2br line as well as initial echo and from there onward, your code actually accomplishes your goal because the explode("\n", $str) is all that you need to split on empty lines and your if statement covers any lines that happen to be only whitespace.
Finally I've solved it using the following code. Thanks everyone for you help.
<?php
$str="category 1
category 2
category 3
category 4
";
$arr = explode("\n", $str);
var_dump($arr);
$result = array();
for($i=0;$i<count($arr);$i++) {
if(!preg_match("/^\s*$/", $arr[$i])) $result[] = $arr[$i];
}
$arr = $result;
var_dump($arr);
for($i = 0; $i < count($arr); $i++){
echo $arr[$i]."</br>";
}?>

How to truncate a delimited string in PHP?

I have a string of delimited numerical values just like this:
5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004| ...etc.
Depending on the circumstance, the string may have only 1 value, 15 values, all the way up to 100s of values, all pipe delimited.
I need to count off (and keep/echo) the first 10 values and truncate everything else after that.
I've been looking at all the PHP string functions, but have been unsuccessful in finding a method to handle this directly.
Use explode() to separate the elements into an array, then you can slice off the first 10, and implode() them to create the new string.
$arr = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$a = explode ('|',$arr);
$b = array_slice($a,0,10);
$c = implode('|', $b);
Use PHP Explode function
$arr = explode("|",$str);
It will break complete string into an array.
EG: arr[0] = 5, arr[1] = 2288 .....
I would use explode to separate the string into an array then echo the first ten results like this
$string = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$arr = explode("|", $string);
for($i = 0; $i < 10; $i++){
echo $arr[$i];
}
Please try below code
$str = '5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324';
$arrayString = explode('|', $str);
$cnt = 0;
$finalVar = '';
foreach ($arrayString as $data) {
if ($cnt > 10) {
break;
}
$finalVar .= $data . '|';
$cnt++;
}
$finalVar = rtrim($finalVar, '|');
echo $finalVar;

Categories