Count how many numbers and letters in the variable using PHP - 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;

Related

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.

In_array not working - compare two files

The code below is a simple version of what I am trying to do. The code will read in two files, see if there is a matching entry and, if there is, display the difference in the numbers for that item. But it isn't working. The first echo displays the word but the second echo is never reached. Would someone please explain what I am missing?
$mainArry = array('Albert,8');
$arry = array('Albert,12');
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
if (in_array($kword[0], $mainArry)) {
echo 'line '.$line. ' has count of '.$kword[1] . '<br>';
}
}
Your $mainArry contains a single element: the string 'Albert,8'. It looks like you want to use it as an array (elements 'Albert' and '8') instead of a string.
You mention the code will read from two files, so you can 'explode' it to a real array, as you do with $arry. A simpler approach would be using str_getcsv() to parse the CSV string into $mainArry.
$inputString = 'Albert,8';
$mainArry = str_getcsv($inputString); // now $mainArry is ['Albert','8']
$arry = array('Albert,12');
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
if (in_array($kword[0], $mainArry)) {
echo 'line '.$line. ' has count of '.$kword[1] . '<br>';
}
}
Test it here.
You are attempting to compare the string Albert with Albert,8, so they won't match. If you want to check if the string contains the keyword, assuming your array has more than one element, you could use:
$mainArry = array('Albert,8');
$arry = array('Albert,12');
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
foreach ($mainArry as $comp) {
if (strstr($comp, $kword[0])) {
echo 'line '.$line. ' has count of '.$kword[1] . '<br>';
}
}
}
example: https://eval.in/728566
I don't recommend your way of working, but this is a solution, basically the process you apply to the $arry should also apply to the $mainArry you're trying to compare it to.
$mainArry = array('Albert,8');
$arry = array('Albert,12');
/***
NEW function below takes the valus out of the main array.
and sets them in their own array so they can be properly compared.
***/
foreach ($mainArry as $arrr){
$ma = explode(",",$arrr);
$names[] = $ma[0];
$values[] = $ma[1];
}
unset($arrr,$ma);
foreach ($arry as $line) {
$kword = explode(',', $line);
echo 'kword '.$kword[0];
/// note var reference here is updated.
if (in_array($kword[0], $names)) {
echo '<br>line '.$kword[0]. ' has count of '.$kword[1] . '<br>';
}
}
Yeah, MarcM's answer above does the same thing in a neat single line, but I wanted to illustrate a little more under the hood operations of the value setting. :-/

How do I get rid of comma after last array item?

I have this array loop:
foreach ( $event_entrance as $event_entrance_s ) {
_e($event_entrance_s,'holidayge');
echo ', ';
}
I'd like to ger rid of comma at the end of the last loop.
Any ideas? Seems simple, but it isn't for me :)
$fn = function($v) { return _e($v,'holidayge'); };
$arr = array_map($fn, $event_entrance );
echo implode(',', $arr);
Two options:
use implode to put things together, it handles this edge case for you easily. Seriously, implode is great
determine if you're on the last element (perhaps with a count, and by accessing the element key) and omit the comma if it's the last element.
What about...
$limit = count($event_entrance);
foreach ($event_entrance as $key => $event_entrance_s) {
_e($event_entrance_s,'holidayge');
if ($key < ($limit-1)) {
echo ', ';
}
}
As long as your keys are integers and sequential, this should work exactly as you intend. If you're using integers, but they are not in any particular order, putting this before your foreach() loop will fix that:
$event_entrance = array_values($event_entrance);
If you are using strings as keys instead of integers, try something like this:
$limit = count($event_entrance);
$i = 1;
foreach ($event_entrance as $event_entrance_s) {
_e($event_entrance_s,'holidayge');
if ($i < $limit) {
echo ', ';
}
++$i;
}
Try something like this:
$event_entrance_count = count($event_entrance);
$loop_number = 1;
foreach ( $event_entrance as $event_entrance_s ) {
_e($event_entrance_s,'holidayge');
if(!$loop_number == $event_entrance_count) {
echo ', ';
}
$loop_number++;
}

how to order in while loop?

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

Make array value variable (PHP)

Say I want to echo an array but I want to make the value in the array I echo variable, how would I do this?
Below is kind of an explanation of what I won't to do but it isn't the correct syntax.
$number = 0;
echo myArray[$number];
I'm not sure what you mean. What you have isn't working because you're missing a $ in myArray:
$myArray = array('hi','hiya','hello','gday');
$index = 2;
echo $myArray[$index]; // prints hello
$index = 0;
echo $myArray[$index]; // prints hi
Unlike other languages, all PHP variable types are preceded by a dollar sign.
Just to add more. Another type of array is associative array, where the element is determined using some identifier, usually string.
$arrayStates = array('NY' => 'New York', 'CA' => 'California');
To display the values, you can use:
echo $arrayStates['NY']; //prints New York
or, you can also use its numeric index
echo $arrayStates[1]; //prints California
To iterate all values of an array, use foreach or for.
foreach($arrayStates as $state) {
echo $state;
}
Remember, if foreach is used on non-array, it will produce warning. So you may want to do:
if(is_array($arrayStates)) {
foreach($arrayStates as $state) {
echo $state;
}
}
Hope that helps!
You are nearly there:
$number = 0;
$myArray = array('a', 'b')
echo $myArray[$number]; // outputs 'a'
$myArray = array("one","two","three","four");
$arrSize=sizeof($myArray);
for ($number = 0; $number < $arrSize; $number++) {
echo "$myArray[$number] ";
}
// Output: one two three four
$myArray = array('hi','hiya','hello','gday');
for($count=0;$count<count($myArray);$count++)
{
$SingleValue = $myArray[$count];
$AllTogether = $AllTogether.",".$SingleValue;
}

Categories