Split a string using foreach? - php

Is it possible to split a string using foreach?
For example my string value is 10
using foreach echos 1,
then echo 2,
then echo 3,
and so on to till it reach the string value.

Yes you can but looking at what you try to achieve, you really don't need to split instead you are trying to increment using loop till the string value reached. In PHP you can cast string to integer and by default PHP will do that for you if you are trying to perform + - * % / operations.
Using Foreach
$string = '10';
$numbers = range(1, $string);
foreach($numbers as $number){
echo $number;
}
Using For
$string = '10';
for($i = 1; $i <= $string; $i++){
echo $i;
}
If splitting string is what your objective, you can use str_split() function and loop like the above foreach()

Related

WP custom field contains 50 names separated by comma: how to just list the first 5?

As stated in the title, in my blog, I own a custom field that - for each post - contains 50 names, but it's way too much, so I'd like to just echo the first 5 names.
I'm trying with this, but it's not working properly...Where am I going wrong?
<?php
$players = get_post_meta($post->ID, 'Names_List', true);
$i = 1;
foreach($players as $player) {
if ($i < 6) {
echo $player;
}
$i++;
}
?>
You are trying to iterate through a string. This means that when you access $players[2] you will get the third character in the string $players.
You will need to convert the string into an array by using the explode function which will break the string into an array based on a character you tell it.
$string = 'This is a string, This is a string 2';
$array = explode(',', $string);
This will break the string into parts based on a comma, resulting in array as follows:
[ 'This is a string', 'This is a string 2' ]
Once you have turned your string into an array, you can then loop through the first 5 by using a for loop and setting it up to only run 5 times.
for($i = 0; $i < 5; $i++) { ... }
This will run the code between the brackets 5 times as we are saying:
Starting $i at 0, whilst $i is less than 5 - Run the code.
After running the code, $i++ will add 1 to $i and test the condition again.
The following code should be able to replace the code from the question and give you the results you want.
$players = get_post_meta($post->ID, 'Names_List', true);
$players_array = explode(',', $players);
for($i = 0; $i < 5; $i++) {
echo $players_array[$i];
if($i < 4) {
echo ',';
}
}
You can use array_slice to get first 5 elements.
Obviously you need to split the string by the comma delimiter with explode first
$players = get_post_meta($post->ID, 'Names_List', true);
$players_array = explode(',', $players);
$first_five = array_slice($players_array, 0, 5);
foreach($first_five as $player)
{
echo $player;
}

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;

Can't do implode method to delimite number range

I have a range of number, say that it from 1 to 10.
//$front_id = 1;
//$until_id = 10;
foreach (range($front_id, $until_id) as $number)
{
print_r($number)
//12345678910
}
It print a range of number between two variables as expected.
However, in the print result is it combine all number without any delimiter.
So, I tried to add a delimiter of comma here:
$numbers = implode(',', $number);
But it doesn't work.
Message: implode(): Invalid arguments passed
You can store $number in array. Right now $number is not an array. That why you cannot implode. Define array first. Then inside foreach() you can store every $number in $numbers array.
$front_id = 1;
$until_id = 10;
$numbers = array();
foreach (range($front_id, $until_id) as $number)
{
$numbers[] = $number;
}
echo implode(',',$numbers);

convert these strings to number

using php. I have the following number
4,564,454
454,454,454
54.54
65.43
I want to convert these into number for calculating. How can I do it? Right now, the type of these number is string.
Note: the comma is not a separate of a number, it is a notion to make a number nicer. I got this format from the ajax request, I cant change the format though. So, I have to use it.
Thanks
$var = floatval(str_replace(",", "", "454,454,454"));
$a='4,5,4';
$ab= explode(',', $a);
foreach ($ab as $b)
{
$sum+=$b; //perform your calculation
}
echo $sum;
First you need to remove ,(comma) from your string as below :
$str=str_replace(",", "", "454,454,454");
Then converting in numeric:
$int = (int)$str;
or
$int=intval($str);
now do your calculation using $int variable.
try this code
$str = '4,564,454';
$str2 = '454,454,454';
$str3= '54.54';
$str4= '65.43';
$sum=0;
$sum += array_sum(explode(',',$str));
$sum += array_sum(explode(',',$str2));
$sum += $str3;
$sum += $str4;
echo $sum;

How to split a number from end to start

How could I split a number from end to start?
Considering that the number can have any length.
The closest thing I tried:
$str = "1234"; #or any other number/string ranging from 0 - 99999
#then somehow inverse the number
$arr1 = str_split($str);
if(!empty($arr1[0])){echo "<div ...>".$arr1[0]."</div>";}
if(!empty($arr1[1])){echo "<div ...>".$arr1[1]."</div>";}
if(!empty($arr1[2])){echo "<div ...>".$arr1[2]."</div>";}
if(!empty($arr1[3])){echo "<div ...>".$arr1[3]."</div>";}
if(!empty($arr1[4])){echo "<div ...>".$arr1[4]."</div>";}
Thank you.
Just use strrev function like this:
<?php
$rev = strrev($str);
?>
Update: One liner to do it all:
$reverse =
array_map(create_function('$n','return "<div...>$n</div>";'), str_split(strrev($str)));
$number = 1234567;
$number = str_split($n);
$numbers = array_reverse($number);
The $number variable is converted to a string if it is not already before being split. Then the array is reversed.
To loop through it:
foreach ($numbers as $value) {
echo "<div ...>".$value."</div>";
}
You can find the length and using the for loop you can extract the numbers one by one.
You can find the length using strlen() and for loop upto strlen()
$str = "1234";
$str = strrev($str);
for($i=0; $i<= strlen($str); $i++){
echo substr($str,$i,1)."<br>";
}

Categories