Related
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
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;
Using the following example in PHP:
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
1) I would like to iterate on the 4 values in $priv. Would 'foreach' be the correct way to do it?
2) If the value is higher than a given number, I would like to echo the index of this value. Not sure how to do it. The comparaison must be INT (not string).
Ex. using "30" it would output:
PAGE_C
PAGE_D
Is it possible? Or maybe I am not using the correct container for what I'm trying to do ?
PS. How would you call the type of "$priv" in this example ? An array ? An indexed variable ? A dictionary ? A list ?
Thank you.
basically:
<?php
function foo($var){
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
$out='';
foreach ($priv as $k=>$v){
if ($v >$var){
$out .= $k.'<br>';
}
}
return $out;
}
echo foo('30');
demo: http://codepad.viper-7.com/GNX7Gf
Just create an array with the letters to iterate over.
$letters = array('A','B','C','D');
for($i=0;$i<count($letters);$i++) {
if($priv['PAGE_' . $letters[$i]] > /*value*/) {
echo $priv['PAGE_' . $letters[$i]];
}
}
$priv is an array.
Also, it's not too clear to me what you are exactly trying to do. Are you trying to echo the value of the array element if it's greater than a constant value?
We could do it using PHP builtin array functions. Its good to use builtin functions if possible in case of performance.
array_walk will do the trick for you. In this case $priv is an associative PHP array. Following is the one line script that will do what you want to achieve:
$input = 30;
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
array_walk($priv, function($value, $key, $input){ if($value > $input) echo $key . '<br>';}, $input);
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];
}
I want to get the count of characters from the following words in the string. For example, if my input is I am John then the output must be like this:
9 // count of 'I am John'
4 // count of 'I am'
1 // count of 'I'
I use the code like this in PHP for this process:
$string = 'I am John';
$words = explode(' ',$string);
$count_words = count($words);
$i =0;
while ($i<$count_words){
if($i==0) {
$words_length[$i] = strlen($words[$i]);
} else {
$words_length[$i] = strlen($words[$i])+1+$words_length[$i-1];
}
echo $words_length[$i]."<br>";
$i++;
}
But it return the output like this:
1
4
9
Why ? Where is my error ? How can I change the ordering ? What does my code must be like ?
Thanks in advance!
If you simply want to have the output in reverse order use array_reverse:
print_r(array_reverse($words_length));
Your problem is that you're looping through the words left to right. You can't output the full length right to left, because each one depends on the words to it's left.
You could take the echo out of the loop, and print the values after all have been calculated.
$string = 'I am John';
$words = explode(' ',$string);
$count_words = count($words);
$i =0;
while ($i<$count_words){
if($i==0) {
$words_length[$i] = strlen($words[$i]);
} else {
$words_length[$i] = strlen($words[$i])+1+$words_length[$i-1];
}
$i++;
}
print implode('<br />', array_reverse($words_length));
The quickest fix is to add print_r(array_reverse($words_length)); after the loop
You may use foreach and array_reverse to get the array values:
foreach(array_reverse($words_length) as $val){
echo $val;
}