Php array display array element 4 per line [duplicate] - php

This question already has answers here:
Selecting multiple array elements
(3 answers)
Closed 1 year ago.
Hey GUys Im beginner to php programming here here i have 15 element in array . i want to display first 4 array element in first line and then second 4 array of element in nextline . i dont know how to achive it here is my code help me on this. thanks in advance
<?php
$arry=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
echo $nr_elm = count($arry); // gets number of elements in $arry
$nr_col = 4; // Sets the number of text Per Line
// If the array has elements
if ($nr_elm > 0)
{
// Traverse the array with FOR
for($i=0; $i<$nr_elm; $i++)
{
echo $textInLine= $arry[$i]. ' | ';
// If the number of columns is completed for a line (rest of division of ($i + 1) to $nr_col is 0)
// Closes the current line, and begins another line
$col_to_add = ($i+1) % $nr_col;
if($col_to_add == 0) { $textInLine .= '/n'; }
}
}
echo $textInLine;
?>

Use array_chunk for this:
$array = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$size = 4;
foreach (array_chunk($array, $size) as $chunk) {
echo implode(' ', $chunk) . PHP_EOL;
}
Another solution without using array_chunk is using modulo:
$array = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$size = 4;
$counter = 0;
foreach ($array as $character) {
echo $character;
// echo new line after every 4th character, a space after the others
echo (++$counter % $size === 0) ? PHP_EOL : ' ';
}

Chunk the array and implode the items in the chunk.
$arry=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$chunks = array_chunk($array, 4);
foreach($chunks as $chunk){
echo implode(" ", $chunk) . "</br>\n";
}
Array_chunk splits the array in to pieces of the size you define.
The resulting array is multidimensional with the items in the subarray.
Implode takes the items in the subarray and adds the delimiter (" ") in between each item and makes it a string.

Use array_chunk, it will Split an array into chunks
<?php
$arry=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
$arr = array_chunk($arry, 4, true);
foreach($arr as $value) {
echo implode(' ', $value) . PHP_EOL ;
}
?>

I don't know if the "15" is intentional, but if you want to remove it just remove the "echo".
I also recommend to use empty() to verify if your array is empty or not, just like this :
if (!empty($arry)) { //Code }
(notice the "!")
Now, for your main question what I would do is using a variable which increments up to 4, then you insert a line break with echo <br>; and reset the variable to 0.
The code should look something like this :
$c = 0;
for($i=0; $i<$nr_elm; $i++)
{
echo $arry[$i];
$c ++;
if ($c >= 4) {
echo "<br>";
$c = 0;
}
}
I hope this helped you

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 add up the total of 1 array + the total of another array

I am a rookie beginner with PHP, i was wondering how i could add up the total number from 1 array + the total number of another array together. I managed to make this code with help from stackoverflow answers on google. I don't know why but it's no where explained or i am looking over it. Been looking for almost an hour to make this work. Here is the code:
<?php
$array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19);
$odds = array();
$even = array();
foreach($array as $val) {
if($val % 2 == 0) {
$even[] = $val;
} else {
$odds[] = $val;
}
}
$array = array();
foreach($even as $key => $val) {
$array[] = $val;
if(isset($odds[$key])) {
$array[] = $odds[$key];
}
}
echo '<b>Oneven</b> ';
print_r($odds);
echo '<br><br><br>';
echo "Bovenstaande <b>oneven</b> getallen bijelkaar opgeteld = " . array_sum($odds) . "\n";
echo '<br><br><br><hr style="margin-top:2%;margin-bottom:4%;">';
/* Array nummer 2 */
$array = array(20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40);
$odds = array();
$even = array();
foreach($array as $val) {
if($val % 2 == 0) {
$even[] = $val;
} else {
$odds[] = $val;
}
}
$array = array();
foreach($even as $key => $val) {
$array[] = $val;
if(isset($odds[$key])) {
$array[] = $odds[$key];
}
}
echo '<b>Even</b> ';
print_r($even);
echo '<br><br><br>';
echo "Bovenstaande <b>even</b> getallen bijelkaar opgeteld = " . array_sum($even) . "\n";
?>
So i don't know how to do it in another way but i have array 1 code at first and then code 2 begins with another array.
The thing is that i want to make a program that includes the odd numbers from 1 to 19 and the even numbers from 20 to 40 and then count the total of those 2 array's. Is there a way to do this in 1 code and count up the total of those 2 array's together. I already have that part of code that it counts the array, in code 1 that is 100 and in code 2 it is 330.
330+100=430 that's the output that i want. Why is that so hard? haha...
I appreciate the help and time effort.
First off, there's a lot of complexity involved in creating the initial array and then extracting only the odd numbers. This complexity can be eliminating by using the range and array_filter functions like so:
$odds = array_filter(range(1, 19), function($elem) {
return $elem & 1;
});
$even = array_filter(range(20, 40), function($elem) {
return $elem % 2 == 0;
});
to calculate sum of the sum of odds plus the sum of even, you can simply merge them together and use array_sum in the same you are doing for the individual arrays
$totalSum = array_sum(array_merge($odds, $even))
As #Darragh pointed out in the comments, you can simplify the array creation by specifying a step parameter for the range function.
$odds = range(1, 19, 2) // start at 1, go up to 19, by increments of 2

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.

How can I echo specific line from a text area using php

I am collecting html text area data to echo in php.I am able to select all data using
$devices = explode("\n", $_POST['devs']);
foreach($devices as $device)
echo $device;
and I am able to select only the first line using:
$first_line = strstr(($_POST['devs']), "\n", true);
echo $first_line;
But How can I echo specific lines ? say line 2 or 4 from text area ?
Usage:
getLines(YOUR POST, START LINE, END LINE(optional));
With return array:
function getLines($text, $start, $end = false)
{
$devices = explode("\n", $text);
$append = "My device is ";
$output = array();
foreach ($devices as $key => $line)
{
if ($key+1 < $start) continue;
if ($end && $key+1 > $end) break;
$output[] = $append.$line;
}
return $output;
}
$array = getLines($_POST['devs'], 2);
var_dump($array);
With echo string:
function getLines($text, $start, $end = false)
{
$devices = explode("\n", $text);
$append = "My device is ";
$output = "";
foreach ($devices as $key => $line)
{
if ($key+1 < $start) continue;
if ($end && $key+1 > $end) break;
$output .= $append.$line."<br />";
}
return $output;
}
echo getLines($_POST['devs'], 2);
Your first code snippet is already creating an array of lines via the explode function.
As such, to output the 2nd and 4th lines, you can simply use:
$devices = explode("\n", $_POST['devs']);
echo $devices[1];
echo $devices[3];
If you're new to PHP (I'm guessing this is the case due to the nature of your question), it should be noted that like many programming languages, arrays are indexed from zero, hence line 2 is 1, line 4 is [3], etc.
UPDATE
To access the penultimate (i.e.: 2nd to last) line, you could use:
echo $devices[count($devices) - 2];
What we're doing here is getting the number of elements in the array (via count) and then subtracting two to fetch the second last element. (As we need to subtract one to deal with the fact that arrays are indexed from zero.)
Do it like this
$nth_line = explode("\n", $_POST['devs'])[n];
where n is you line no.
the explode() returns an array then you can select each element by basic array operation
further readings http://php.net/manual/en/function.explode.php
because $devices is an array after exploding it, you can treat each line by it's index. Reminder that arrays are zero-index based so 1 starts at 0.
$devices = explode('\n', $_POST['devs']);
// line 1
echo $devices[0];
// line 2
echo $devices[1];
// line 4
echo $devices[3];
you can use split:
$lines = split("\n", $_POST['devs']);
echo $lines[3]; //4th line
See documentation http://php.net/manual/es/function.split.php
Take a look at array operations in PHP. Since $devices is an array you can select an element by its index like this: $devices[1] for second element, $devices[2] for third etc.
Lookup your syntax on php.net. It is
$devices = explode(";", "aap;noot;mies");
print_r($devices);
foreach ($devices as $key => $value) {
echo "<br>nr.$key=" . $devices[$key];
}

php basic operations question

I have a array of say 50 elements. This array can be of size anything.
I want to have the first 10 elements of the array in a string.
I have the program as:
$array1= array("itself", "aith","Inside","Engineer","cooool","that","it","because");
$i=0;
for($f=0; $f < sizeof(array1); $f++)
{
$temparry = $temparry.array1[$f];
if(($f%10) == 0 && ($f !== 0))
{
$temparray[$i] = $temparray;
$i++;
}
}
==
so that at the end:
I get
temparray1= first 10 elements
temparray2 - next 10 elemnts...
I am not what I am missing in my loops.
After reading your comment, I think you want array_chunk [docs]:
$chunks = array_chunk($array1, 10);
This will create a multidimensional array with each element being an array containing 10 elements.
If you still want to join them to a string, you can use array_map [docs] and implode [docs]:
$strings = array_map('implode', $chunks);
This gives you an array of strings, where each element is the concatenation of a chunk.
This is something you can easily do with array_splice and implode.
Example:
<?php
$array = range(1, 50);
while ( $extracted = array_splice($array, 0, 10) )
{
// You could also assign this to a variable instead of outputting it.
echo implode(' ', $extracted);
}
all you are doing here is creating a temporary value and then deleting it. To save it into a string:
$myArray = array("itself", "aith","Inside","Engineer",
"cooool","that","it","because");
$myString = '';
for($i = 0; $i < 10; $i++) {
$myString .= $myArray[$i];
}
You could also run that inside of another for loop that would run through the entire array giving you ten-element increments.
Actually you can use arrray_slice and implode functions like this:
// put first 10 elements into array output
$output = array_slice($myArray, 10);
// implode the 10 elements into a string
$str = implode("", $output);
OP's fixed code as per comments below:
$array1= array("itself","aith","Inside","Engineer","cooool","that","it","because");
$temparry='';
$temparray = array();
for($f=0; $f < count($array1); $f++)
{
$temparry = $temparry.$array1[$f];
if(($f%3) == 0 && ($f !== 0))
{
$temparray[] = $temparry;
$temparry = '';
}
}
print_r($temparray);

Categories