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);
Related
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;
}
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()
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;
I have an array of about 100 different random number like this:
$numbers=array(10,9,5,12, ..... .... ... ...);
now i want to make an array of random numbers from this array so that addition of selected numbers will be my given number. example: i may ask to get array of numbers such that, if i add all numbers it will be 100.
i am trying to do it in this way,
function rendom_num ($array,$addition)
{
//here is the code
}
print_r (rendome_num ($numbers,100));
i am not able to fiend the code for last 3 days!
Please use shuffle-
<?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}
?>
php.net
can use shuffle as #chatfun said or can try array_rand if want only some random values from your array
$value= array("Rabin","Reid","Cris","KVJ","John");
$rand_keys=array_rand($value,2);
echo "First random element = ".$value[$rand_keys[0]];
echo "<br>Second random element = ".$value[$rand_keys[1]];
Something like this should work. The breakdown is commented so you know what it's all doing.
function Randomizer($number = 100)
{
// This just generates a 100 number array from 1 to 100
for($i=1; $i <= 100; $i++) {
$array[] = $i;
}
// Shuffles the above array (you may already have this array made so you would need to input into this function)
shuffle($array);
// Assign 0 as base sum
$sum = 0;
// Go through the array and add up values
foreach($array as $value) {
// If the sum is not the input value and is also less, continue
if($sum !== $number && $sum < $number) {
// Check that the sum and value are not greater than the input
if(($sum + $value) <= $number) {
// If not, then add
$sum += $value;
$new[] = $value;
}
}
// Return the array when value hit
else
return $new;
}
// If the loop goes through to the end without a successful addition
// Try it all again until it does.
if($sum !== $number)
return Randomizer($number);
}
// Initialize function
$test = Randomizer(100);
echo '<pre>';
// Total (for testing)
echo array_sum($test);
// Array of random values
print_r($test);
echo '</pre>';
I get these numbers seperated by commas from a textarea but I get an error when I try to loop through them. How do I do it? This is my code:
$numbers = $_GET['numbers'];
foreach($numbers as $number){
echo $number;
}
You should first make an array out of $numbers. You can do this by adding this line:
$numbers = explode(',', $_GET['numbers']);
Then, before you use them in the foreach loop you should use trim() to remove whitespace from the start and end:
foreach($numbers as $number){
$number = trim($number);
echo $number
}
If $_GET['numbers'] is a comma-separated list, it's not an array.
foreach(explode(",",$_GET['numbers']) as $number)