Trying to remove the comma that comes after the number 10. Tried every plausible workaround, but nothing's worked so far.
$i = 0;
while($i < 10) {
echo ++$i. ",";
}
Don't use a loop in the first place. Use implode() to insert a delimiter between array elements.
echo implode(',', range(1, 10));
You can do it using loop and rtrim() like this:
$i = 0;
$result = '';
while($i < 10) {
$result .= ++$i. ",";
}
echo rtrim($result, ',');
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;
}
I have an array which has nested String that I want to output without a loop.
Here is the array:
$field_my_array[0]['string_term']->name = "First";
$field_my_array[1]['string_term']->name = "Second";
$field_my_array[2]['string_term']->name = "Third";
$field_my_array[3]['string_term']->name = "Forth";
$field_my_array[4]['string_term']->name = "Fifth";
I want to output this as
First, Second, Third, Forth, Fifth
This is what I tried (but it's in loop)
for ($ctr = 0; $ctr < count($field_my_array); $ctr ++) {
print $field_my_array[$ctr]['string_term']->name;
if ($ctr < count($field_my_array) -1) {print ", ";}
}
I'd be inclined to break this down into two parts:
Convert the array into a simplified version that just contains the values you want to concatenate. For that, you can use array_map() (https://www.php.net/manual/en/function.array-map.php).
Join the elements of the array without an extra comma on the end. The perfect use case for implode() (https://www.php.net/manual/en/function.implode.php).
Example:
echo implode(', ', array_map(function($item) {
return $item['string_term']->name;
}, $field_my_array));
I am not sure what you're trying to achieve. If you don't want to loop, then you have to manually write like this:
echo $field_my_array[0]['string_term']->name;
echo ", ";
echo $field_my_array[1]['string_term']->name;
...
and so on. Looping is a fundamental programming construct that allows us to automate with a simple count.
for ($ctr = 0; $ctr < count($field_my_array); $ctr ++) {
print $field_my_array[$ctr]['string_term']->name;
if ($ctr < count($field_my_array) -1) {print ", ";}
}
A better one would be this:
$field_my_array[0]['string_term']->name = "First";
$field_my_array[1]['string_term']->name = "Second";
$field_my_array[2]['string_term']->name = "Third";
$field_my_array[3]['string_term']->name = "Forth";
$field_my_array[4]['string_term']->name = "Fifth";
$names = array();
for ($ctr = 0; $ctr < count($field_my_array); $ctr ++) {
$names[] = $field_my_array[$ctr]['string_term']->name;
}
// this creates a string with a comma between items from array
$full_text = implode(', ',$names);
echo $full_text ;
You can use array_merge_recursive with implode
$c = array_merge_recursive(...$field_my_array);
echo implode(',', $c['string_term']['name']);
Live DEMO https://3v4l.org/GdhM5
How I can get $lorem_text as a new string $lorem_outside_text without changing $lorem_text?
for ($i = 0; $i <= 5; $i++) {
$lorem_text = "lorem\n";
}
$lorem_outside_text = $lorem_text;
echo $lorem_outside_text;
Now result is: lorem
Result should be: lorem lorem lorem lorem lorem
With this piece of code you are overwriting your existing value every time.
for ($i = 0; $i <= 5; $i++) {
$lorem_text = "lorem\n"; // this just overwrites $lorem_text value 6 times with same value
}
Instead try to concatenate it using . and also remove extra using of variables here $lorem_outside_text
$lorem_outside_text = ''; //intialize it as empty string
for ($i = 0; $i <= 5; $i++) {
$lorem_outside_text .= "lorem\n";
}
echo $lorem_outside_text;
Pretty Neat:
<?php
echo str_repeat("lorem\n", 6);
?>
DEMO: https://3v4l.org/CIsCB
You may use concatenating assignment operator, Please try the following code:
$lorem_text .= "lorem\n";
$lorem_outside_text = '';
for ($i = 0; $i <= 5; $i++) {
$lorem_outside_text .= $lorem_text;
}
echo $lorem_outside_text;
You must append the text to the $lorem_text, not overwrite it. Type .= instead of =.
Personally, I'm usually adding text fragments to an array inside a loop, and then concatenate them using implode("\n", $lorem_parts).
Just use str_repeat, that will repeat the string however many times you want.
str_repeat($lorem_text, 5);
Another option is to create an array in the loop that you later implode.
for ($i = 0; $i <= 5; $i++) {
$lorem_text[] = "lorem";
}
echo implode("\n", $lorem_text);
Implode takes an array and uses the glue to make it string.
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>";
}?>
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;