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

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

Related

Remove the last part of the comma in foreach in PHP?

How can I prevent the insertion of a comma at the end of the title3?
foreach ($_POST['titles'] AS $title) {
echo "{$title},";
};
Result:
title1,title2,title3,
Update :
It comes as a form data, this is array. Don't come this way; title1,title2,title3,
<form>
<select name="titles[]">
<option>title1</title>
<option>title2</title>
<option>title3</title>
<option>title4</title>
</select>
</form>
just use implode() - which is the equivalent to .join():
echo implode(',', $_POST['titles']);
or simply:
echo implode($_POST['titles']);
if you really want to use a loop - an index is required in order to determine the last one element. a foreach loop does not provide any index to compare to; that's why a for loop is rather suitable:
// $titles = explode(',', $_POST['titles']);
$titles = $_POST['titles'];
for($i=0; $i < sizeof($titles); $i++) {
echo $titles[$i];
if($i+1 != sizeof($titles)){echo ',';}
}
looks like you could skip the foreach altogether and just do this:
echo implode(',',$_POST['titles']);
You should use implode instead.
$string = implode(',', $_POST['titles']);
I agree with the other answers - implode() is the way to go. But if you'd rather not/keep on the path you're on...
$output = "";
foreach ($_POST['titles'] AS $title) {
$output .= "{$title},";
};
echo substr($output, 0, -1);

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;

Listing an array of data ordered by how often they appear [duplicate]

Say I have an array like this:
$array = array('', '', 'other', '', 'other');
How can I count the number with a given value (in the example blank)?
And do it efficiently? (for about a dozen arrays with hundreds of elements each)
This example times out (over 30 sec):
function without($array) {
$counter = 0;
for($i = 0, $e = count($array); $i < $e; $i++) {
if(empty($array[$i])) {
$counter += 1;
}
}
return $counter;
}
In this case the number of blank elements is 3.
How about using array_count _values to get an array with everything counted for you?
Just an idea, you could use array_keys( $myArray, "" ) using the optional second parameter which specifies a search-value. Then count the result.
$myArray = array( "","","other","","other" );
$length = count( array_keys( $myArray, "" ));
I dont know if this would be faster but it's something to try:
$counter = 0;
foreach($array as $value)
{
if($value === '')
$counter++;
}
echo $counter;
You could also try array_reduce, with a function which would just count the value you are interested in. eg
function is_empty( $v, $w )
{ return empty( $w ) ? ($v + 1) : $v; }
array_reduce( $array, 'is_empty', 0 );
Some benchmarking might tell you if this is faster than array_count_values()
We use array_filter function to find out number of values in array
$array=array('','','other','','other');
$filled_array=array_filter($array);// will return only filled values
$count=count($filled_array);
echo $count;// returns array count
Generally for counting blanks only.
Really depends on use case and speed needed. Personally I like doing things one one line.
Like the chosen response though But you still need a line to extract the data needed though to another variable.
$r = count($x) - count(array_filter($x));
function arrayvaluecount($array) {
$counter = 0;
foreach($array as $val){
list($v)=$val;
if($v){
$counter =$counter+1;
}
}
return $counter;
}
function countarray($array)
{ $count=count($array);
return $count;
}
$test=$array = array('', '', 'other', '', 'other');
echo countarray($test);

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'], ", ");

Count number of values in array with a given value

Say I have an array like this:
$array = array('', '', 'other', '', 'other');
How can I count the number with a given value (in the example blank)?
And do it efficiently? (for about a dozen arrays with hundreds of elements each)
This example times out (over 30 sec):
function without($array) {
$counter = 0;
for($i = 0, $e = count($array); $i < $e; $i++) {
if(empty($array[$i])) {
$counter += 1;
}
}
return $counter;
}
In this case the number of blank elements is 3.
How about using array_count _values to get an array with everything counted for you?
Just an idea, you could use array_keys( $myArray, "" ) using the optional second parameter which specifies a search-value. Then count the result.
$myArray = array( "","","other","","other" );
$length = count( array_keys( $myArray, "" ));
I dont know if this would be faster but it's something to try:
$counter = 0;
foreach($array as $value)
{
if($value === '')
$counter++;
}
echo $counter;
You could also try array_reduce, with a function which would just count the value you are interested in. eg
function is_empty( $v, $w )
{ return empty( $w ) ? ($v + 1) : $v; }
array_reduce( $array, 'is_empty', 0 );
Some benchmarking might tell you if this is faster than array_count_values()
We use array_filter function to find out number of values in array
$array=array('','','other','','other');
$filled_array=array_filter($array);// will return only filled values
$count=count($filled_array);
echo $count;// returns array count
Generally for counting blanks only.
Really depends on use case and speed needed. Personally I like doing things one one line.
Like the chosen response though But you still need a line to extract the data needed though to another variable.
$r = count($x) - count(array_filter($x));
function arrayvaluecount($array) {
$counter = 0;
foreach($array as $val){
list($v)=$val;
if($v){
$counter =$counter+1;
}
}
return $counter;
}
function countarray($array)
{ $count=count($array);
return $count;
}
$test=$array = array('', '', 'other', '', 'other');
echo countarray($test);

Categories