How to read lines of numbers through string? (inside a loop) - php

I got help from a group user with the previous question, but instead of reading the lines from a txt file, i want to read the lines of numbers from a string.
1 and until 119
How can this be done?
Through txt file it works:
$lines = file("lines.txt");
if($i==119)
...
through string does not.
$numbers = "1
2
4
5
..."
for($i = 119; $i >= 0; $i--)
{
$lines = "$numbers";
if($i==119)
{
$no_of_lines = round(count($lines)/14);
}
$line = $lines["$i"];
echo "$line<br>";
if( $i % 14 === 0 )
{
echo "$no_of_lines<br>";
$no_of_lines--;
}
}

To access your string you either need to know the position in the string where you could use substr but when your numbers get to 10 and beyond the length of 1 digit you can't know the position of each number.
So you could use explode to create an array called $lines delimited by a space (if all your numbers are separated by a space:-
$lines= explode(" ", $numbers);
so then your code could be :-
<?php
$numbers = "1 2 3 4 5 6";
$lines= explode(" ", $numbers);
for($i = 0; $i < count($lines); $i++) {
$line = $lines[$i];
echo "$line<br>";
}
echo "<br>No_of_lines = " . count($lines);
?>
Which gives as your output :-
1
2
3
4
5
6
No_of_lines = 6

Related

how to search for consecutive repeated characters in a string without using any built-in php functions?

I have been asked to solve this question. Please suggest me how to solve this.
$string = "kkjnmnmnjjjnmn";
here I need to find consecutively repeated string of length 3. for example - kkj has occurred only once and jnm 2 times and nmn 3 times.
Starting from first character, going in right side direction, 3 consecutive characters which are repeated more than once should be the output.
Preg_match_all will result as nmn - 2 times and not as 3 times.
How to solve this?
$string = "kkjnmnmnjjjnmn";
$length = strlen($string);
$pieces = [];
for ($i = 0; $i < $length - 2; $i++) {
$piece = substr($string, $i, 3);
if (array_key_exists($piece, $pieces)) {
$pieces[$piece] += 1;
} else {
$pieces[$piece] = 1;
}
}
// $pieces will contain what you need
This one without using any build in functions, Try
$string = "kkjnmnmnjjjnmn";
$i = 0;
$strarr = array();
while(isset($string[$i+2])){
if(!isset($strarr[$string[$i].$string[$i+1].$string[$i+2]]))
$strarr[$string[$i].$string[$i+1].$string[$i+2]] = 1;
else
$strarr[$string[$i].$string[$i+1].$string[$i+2]] += 1;
$i++;
}
print_r($strarr);
Here's my thought.
$arr = array();
for ($i = 0; $i <= strlen($string) - 3; $i++) {
$part = substr($string, $i, 3);
if (array_key_exists($part, $arr)) {
$arr[$part]++;
} else {
$arr[$part] = 1;
}
}
foreach ($arr as $key => $value) {
//output the result
}
well iam not a php expert but after examine the previous answers,i found an alter solution too here it is:
$string='aaaabcdeeeffaaabh';
$arr_str=array();
for($i=0;$i<strlen($string);$i++)
{
if(in_array($string[$i],$arr_str[$char[$i]]))
{
$arr_str[$string[$i]]=1;
}
else
{
$arr_str[$string[$i]]+=1;
}
}
foreach($arr_str as $key => $value)
{
echo $key.' Repeats '.$value.' Times'.'<br/>';
}
OUTPUT:
a Repeats 7 Times
b Repeats 2 Times
c Repeats 1 Times
d Repeats 1 Times
e Repeats 3 Times
f Repeats 2 Times
h Repeats 1 Times

Creating arrays in a for loop via list()?

$$I have a bunch fo text files I'd like to eventually explode into arrays, but since the amount of text files is dynamically chosen via user input, I can't just initialize them one-by-one and instead am opting for a for loop.
For the sake of example, three text files I have contain the following (excuse the \n, imagine it's a line break):
file1.txt = 1 \n 2 \n 3
file2.txt = 6 \n 2 \n 7
file3.txt = 9 \n 1 \n 9
The code I attempted:
<?php
for ($i = 1; $i <= 3; $i++) {
list($line1[$i], $line2[$i], $line3[$i]) = file("public_html/texts/file".$i.".txt");
?>
This obviously doesn't work, but I'm not sure why. In the end, the result should be:
$line1[1] = 1
$line2[1] = 2
$line3[1] = 3
$line1[2] = 6
$line2[2] = 2
$line3[2] = 7
$line1[3] = 9
$line2[3] = 1
$line3[3] = 9
How do I go about doing this?
edit; fixed typo.
You have an error in your code, see:
file("public_html/texts/file".&i.".txt");
^-- TYPO HERE
for($i = 1; $i <= 3; $i++) {
$lines = file('public_html/texts/file' . $i . '.txt');
$line1[] = $lines[0];
$line2[] = $lines[1];
$line3[] = $lines[2];
}

Creating files based on the line number for printing

I have following data extracted from the MySQL database to create labels.
BREAK
Name:RAJ
Company:ABC
Order Number:101
Order Details:
Item1
Item20
Item3
BREAK
Name:RAJ
Company:ABC
Order Number:101
Order Details:
2 x Item1
2 x Item2
2 x Item3
BREAK
Name:RAJ
Company:ABC
Order Number:101
Order Details:
5 x Item4
5 x Item5
5 x Item2
I wrote some code to find the position of BREAK in PHP and it can generate lines number like below.
2
14
26
36
I want a file for the contents that are between line 2 and 14 in one file and 26 to 36 in one file. I am working in php and tried using sed from shell_exec function however if I read this output and generate sed command, I don't get first 2 number together.
What I am expecting is below.
sed -n 2,14p file1.txt
sed -n 26,36p file2.txt
Any suggestion either in php or shell script?
Use array_slice() for getting ranges in an array.
My solution is very hard coupled to your requirements, meaning every first line is a starting range number and the following the end range.
// the lines from which will be read
$lines = "1
5
16
26";
// split these numbers above into an array
$lines = explode(PHP_EOL, $lines);
// the source file where the ranges will be taken off
$file = file('file.txt');
for($i = 0; $i < count($lines); $i+=2) {
$rangeStart = $lines[$i];
$rangeLength = $lines[$i+1] - $lines[$i];
// slice out the ranges, beware the second parameter is the length not the offset!
$ranges[] = array_slice($file, $rangeStart, $rangeLength);
}
print_r($ranges);
But it would be a lot easier to do it automatically on your source file/text/string (?) directly, if this is possible.
$file = file('file.txt');
$len = count($file);
$output = array();
$current = array();
for($i = 0; $i < $len; $i++) {
$data = trim($file[$i]);
if ($data != 'BREAK') {
$current[] = $data;
} else {
$output[] = implode(PHP_EOL, $current);
$current = array();
}
}
print_r($output);

How do I distribute values of an array in three columns?

I need this output..
1 3 5
2 4 6
I want to use array function like array(1,2,3,4,5,6). If I edit this array like array(1,2,3), it means the output need to show like
1 2 3
The concept is maximum 3 column only. If we give array(1,2,3,4,5), it means the output should be
1 3 5
2 4
Suppose we will give array(1,2,3,4,5,6,7,8,9), then it means output is
1 4 7
2 5 8
3 6 9
that is, maximum 3 column only. Depends upon the the given input, the rows will be created with 3 columns.
Is this possible with PHP? I am doing small Research & Development in array functions. I think this is possible. Will you help me?
For more info:
* input: array(1,2,3,4,5,6,7,8,9,10,11,12,13,14)
* output:
1 6 11
2 7 12
3 8 13
4 9 14
5 10
You can do a loop that will automatically insert a new line on each three elements:
$values = array(1,1,1,1,1);
foreach($values as $i => $value) {
printf('%-4d', $value);
if($i % 3 === 2) echo "\n";
}
EDIT: Since you added more information, here's what you want:
$values = array(1,2,3,4,5);
for($line = 0; $line < 2; $line++) {
if($line !== 0) echo "\n";
for($i = $line; $i < count($values); $i+=2) {
printf('%-4d', $values[$i]);
}
}
And if you want to bundle all that in a function:
function print_values_table($array, $lines = 3, $format = "%-4d") {
$values = array_values($array);
$count = count($values);
for($line = 0; $line < $lines; $line++) {
if($line !== 0) echo "\n";
for($i = $line; $i < $count; $i += $lines) {
printf($format, $values[$i]);
}
}
}
EDIT 2: Here is a modified version which will limit the numbers of columns to 3.
function print_values_table($array, $maxCols = 3, $format = "%-4d") {
$values = array_values($array);
$count = count($values);
$lines = ceil($count / $maxCols);
for($line = 0; $line < $lines; $line++) {
if($line !== 0) echo "\n";
for($i = $line; $i < $count; $i += $lines) {
printf($format, $values[$i]);
}
}
}
So, the following:
$values = range(1,25);
print_array_table($values);
Will output this:
1 10 19
2 11 20
3 12 21
4 13 22
5 14 23
6 15 24
7 16 25
8 17
9 18
One solution is to cut the array into chunks, representing the columns, and then print the values in row order:
$cols = array_chunk($arr, ceil(count($arr)/3));
for ($i=0, $n=count($cols[0]); $i<$n; $i++) {
echo $cols[0][$i];
if (isset($cols[1][$i])) echo $cols[1][$i];
if (isset($cols[2][$i])) echo $cols[2][$i];
}
If you don’t want to split your array, you can also do it directly:
for ($c=0, $n=count($arr), $m=ceil($n/3); $c<$m; $c++) {
echo $arr[$c];
for ($r=$m; $r<$n; $r+=$m) {
echo $arr[$c+$r];
}
}
$a = array(1,2,3,4,5);
"{$a[0]} {$a[1]} {$a[2]}\n{$a[3]} {$a[4]}";
or
$a = array(1,2,3,4,5);
"{$a[0]} {$a[1]} {$a[2]}".PHP_EOL."{$a[3]} {$a[4]}";
or
$a = array(1,2,3,4,5);
$second_row_start = 3; // change to vary length of rows
foreach( $a as $index => $value) {
if($index == $second_row_start) echo PHP_EOL;
echo "$value ";
}
or, perhaps if you want a longer array split into columns of 3?
$a = array(1,2,3,4,5,6,7,8,9,10,11,12,13);
$row_length = 3; // change to vary length of rows
foreach( $a as $index => $value) {
if($index%$row_length == 0) echo PHP_EOL;
echo "$value ";
}
which gives
1 2 3
4 5 6
7 8 9
10 11 12
13
one solution is :
your array has N elements, and you want 3 columns, so you can get the value of each cell with $myarray[ column_index + (N/3) + line_index ] (with one or two loops for columns and lines, at least for lines)
I hope this will help you
Bye
Here's something I whipped up. I'm pretty sure this could be more easily accomplished if you were using HTML lists, I've assumed you can't use them.
$arr = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14, 15, 16);
$max = count($arr);
$cols = 3;
$block = ceil($max / $cols);
for ($i = 0; $i < $block ; $i++) {
echo $arr[$i] . ' ';
for ($j = 1; $j < $cols; $j++) {
$nexKey = $i + $block * $j;
if (!isset($arr[$nexKey])) break;
echo $arr[$nexKey] . ' ';
}
echo '<br>';
}
NOTE : You can easily refactor the code inside the loop that uses $nexkey variable by making it into a loop itself so that it works for any number of columns. I've hardcoded it.
Uses loops now.

PHP function to loop thru a string and replace characters for all possible combinations

I am trying to write a function that will replace characters in a string with their HTML entity encoded equivalent.
I want it to be able to go through all the possible combinations for the given string, for example:
go one-by-one
then combo i.e.. 2 at a time, then three at a time, till you get length at a time
then start in combo split, i.e.. first and last, then first and second to last
then first and last two, fist and second/third last
So for the characters "abcd" it would return:
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
etc.......... so on and so forth till there are no other combinations
Any ideas, or has anyone seen a function somewhere I could modify for this purpose?
loop from 0 to 2^length - 1. On each step, if Nth bit of the loop counter is 1, encode the Nth character
$str = 'abcd';
$len = strlen($str);
for($i = 0; $i < 1 << $len; $i++) {
$p = '';
for($j = 0; $j < $len; $j++)
$p .= ($i & 1 << $j) ? '&#' . ord($str[$j]) . ';' : $str[$j];
echo $p, "\n";
}
There are 2^n combinations, so this will get huge fast. This solution will only work as long as it fits into PHP's integer size. But really who cares? A string that big will print so many results you'll spend your entire life looking at them.
<?php
$input = 'abcd';
$len = strlen($input);
$stop = pow(2, $len);
for ($i = 0; $i < $stop; ++$i)
{
for ($m = 1, $j = 0; $j < $len; ++$j, $m <<= 1)
{
echo ($i & $m) ? '&#'.ord($input[$j]).';' : $input[$j];
}
echo "\n";
}
How about this?
<?php
function permutations($str, $n = 0, $prefix = "") {
if ($n == strlen($str)) {
echo "$prefix\n";
return;
}
permutations($str, $n + 1, $prefix . $str[$n]);
permutations($str, $n + 1, $prefix . '&#' . ord($str[$n]) . ';');
}
permutations("abcd");
?>

Categories