accept input from user and display array and multiplication (CLOSE) - php

This is the code of accept input from user and display array and multiplication and put it in table form.
<?php
if(isset($_POST['submit']))
{
$n1 = $_POST['num1'];
$n2 = $_POST['num2'];
}
else
{
$n1 = 0;
$n2 = 0;
}
function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
$numbers = range($min, $max);
shuffle($numbers);
return array_slice($numbers, 0, $quantity);
}
$numberArray = array(
UniqueRandomNumbersWithinRange(1,10,$n1),
UniqueRandomNumbersWithinRange(1,10,$n2))
?>
<form action="" method="post">
<input type="text" name="num1" placeholder="value 1"><br>
<input type="text" name="num2" placeholder="value 2"><br>
<input type="submit" name="submit">
</form>
<?php
printTable($numberArray); //panggilan function apa yg nk tunjuk
function printTable($numberArray) {
// Placeholder
$result = [];
// Setup the multiply
foreach ($numberArray[1] as $key1 => $value1) {
$tmp = array($value1); // add index y-axis
foreach ($numberArray[0] as $key0 => $value0) {
$tmp[] = $value0 * $value1;
}
$result[] = $tmp;
}
// Add index the x-axis
array_unshift($result, array_merge(array(" "), $numberArray[0]));
// display the result into table form
echo "<table border='1' align='center'>";
foreach ($result as $key => $value) {
echo "<tr>";
foreach ($value as $k => $v) {
if ($k == 0 || $key == 0) {
echo sprintf("<td><b>%s</b></td>", $v);
continue;
}
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
}
?>
Here can accept insert from user and auto generate number in array form which means user enter 5 in the textbox1 and 6 in the textbox2, it will generate number 3,4,5,2,1 and 2,3,4,1,2,3.
How I can capture this number put inside
$numberArray = array(
array($display1),
array($display2)
);

Related

How to limit array in array

I want to limit every array to strings with 15 characters or less. I have tried this code, but it does not work:
$a = [
"name1" => ['Dewa','Aditya','Pratama'],
"name2" => ['Brian','Dzikri','Ramadhan'],
];
$result_shortdes = "";
foreach ($a as $values) {
foreach ($values as $value) {
if(strlen($result_shortdes) + strlen($value) <= 15)
{
$result_shortdes .= "$value,";
}
}
}
echo '<pre>';
print_r($result_shortdes);
echo '<pre>';
My expected output is like this:
1. Dewa,Aditya,
2. Brian,
Every time you go to the next name, you need to reset result_shortdes to count the name length again, place the variable inside the first loop like this:
foreach ($a as $values) {
$result_shortdes = "";
foreach ($values as $value) {
if(strlen($result_shortdes) + strlen($value) <= 15)
{
$result_shortdes .= "$value,";
}
}
echo '<pre>';
print_r($result_shortdes);
echo '<pre>';
}
you can use $result_shortdes for length and $result to store result like below
$a = [
"name1" => ['Dewa','Aditya','Pratama'],
"name2" => ['Brian','Dzikri','Ramadhan'],
];
$result_shortdes = "";
$result = [];
foreach ($a as $values) {
$result_shortdes = "";
foreach ($values as $value) {
if(strlen($result_shortdes) + strlen($value) <= 15)
{
$result_shortdes .= "$value,";
}else{
$result[] = $result_shortdes;
break;
}
}
}
echo '<pre>';
print_r($result);
echo '<pre>';

Output the array such that

I am making a program that will output an array in ascending order BUT if there found matching number it will skip that and consider that later.
for example:
array = 2, 1, 3, 1, 5, 2;
output should be:
array = 1, 2, 3, 5, 1, 2 //first four sequence number(1,2,3,5) and then repeating number sequenced later.
Here is my code
<?php
if(isset($_POST['submit'])) {
$var = $_POST['in'];
$arr = explode(" ",$var);
sort($arr);
$size = sizeof($arr);
$arr2 = array();
$cnt=0;
$k=0;
for($i=0;$i<$size;$i++)
{
for($j=0;$j<$size;$j++) {
$k = $j + 1;
if($arr[$j] < $arr[$k]) {
$arr2[$j] = $arr[$j];
array_splice($arr,$j,1);
}
if($arr[$j] == $arr[$k]) {
continue;
$cnt++;
}
if($cnt==0) {
break;
}
}
}
foreach($arr2 as $value) {
echo " ".$value;
}
}
?>
<html>
<head></head>
<body>
<form method="post">
<h2>Enter data</h2>
<input type="text" name="in" placeholder="Enter data with spaces.."/>
<input type="submit" value="ok" name="submit"/>
</form>
</body>
</html>
It is not working. please correct the code.
Thanks
Please Try this:
$myArr = [] //with values 2, 1, 3, 1, 5, 2;
$tmp = $tmp2 = [];
foreach($myArr as $val){
if(!in_array($val, $tmp)){
$tmp[] = $val;
}else{
$tmp2[] = $val;
}
}
$finalArr = array_merge($tmp, $tmp2); // your desired output
Try this:
$arr = array( 2, 1, 3, 1, 5, 2,2);
$groups = array(array());
foreach($arr as $a) {
$found = false;
foreach($groups as &$g) {
if(in_array($a, $g)) {
continue;
}
$g[] = $a;
$found = true;
break;
}
if(!$found) {
$groups[] = array($a);
}
}
foreach($groups as &$g) {
sort($g);
}
$result = array();
foreach($groups as &$g) {
$result = array_merge($result, $g);
}
var_dump($result);
it will work for unlimited duplicates
You can try it here

how to display multi dimension with 2 array and multiply it

This is the code to display multi dimension with array
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$numberArray = array(
array(1, 2, 3, 4, 7, 6),
array(2, 3, 1, 0, 5)
);
function printTable($numberArray) {
// Placeholder
$result = [];
// Setup the multiplication
foreach ($numberArray[1] as $key1 => $value1) {
$tmp = array($value1); // add index y-axis
foreach ($numberArray[0] as $key0 => $value0) {
$tmp[] = $value0 * $value1;
}
$result[] = $tmp;
}
// Add index the x-axis
array_unshift($result, array_merge(array(" "), $numberArray[0]));
// Loop through the $result array and display the table
echo "<table border='1'>";
foreach ($result as $key => $value) {
echo "<tr>";
foreach ($value as $k => $v) {
if ($k == 0 || $key == 0) {
echo sprintf("<td><b>%s</b></td>", $v);
continue;
}
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
}
?>
</body>
</html>
Example of output: https://gyazo.com/2a0a5c07ac75f285f6b8a4631d5b723c
How to display the multi dimension with array and inside the answer will be multiply between numbers.
Looking at the links to the screenshots you provided, maybe this setup can help you:
<?php
$numberArray = array(
array(1, 2, 3, 4, 7, 6),
array(2, 3, 1, 0, 5)
);
function printTable($numberArray)
{
// Placeholder
$result = [];
// Setup the multiplication
foreach ($numberArray[1] as $key1 => $value1) {
$tmp = array($value1); // add index y-axis
foreach ($numberArray[0] as $key0 => $value0) {
$tmp[] = $value0 * $value1;
}
$result[] = $tmp;
}
// Add index the x-axis
array_unshift($result, array_merge(array(" "), $numberArray[0]));
// Loop through the $result array and display the table
echo "<table border='2'>";
foreach ($result as $key => $value) {
echo "<tr>";
foreach ($value as $k => $v) {
if ($k == 0 || $key == 0) {
echo sprintf("<td><b>%s</b></td>", $v);
continue;
}
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
}

PHP - Detect change on string

I have an array which i do a foreach($array as $key => $value)
in my $key i get
name[1][1]
name[1][2]
name[1][3]
name[2][1]
name[2][2]
how can I add detect when the first index changes from [1][3]->[2][1]
any help is appreciated.
What i want to achieve is this:
<h4>Header</h4>
name[1][1]
name[1][2]
name[1][3]
<h4>Header</h4>
name[2][1]
name[2][2]
<h4>Header</h4>
name[3][1]
name[3][2]
name[3][3]
name[3][4]
Don't know if it is the best option, but this is how i managed to do it.
<?php $k = 1; $flag1 = 0; $flag2 = 1;foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?>
<?php
$endpos = strpos($option_name,']');
$asd = substr($option_name,5,$endpos-5);
$this->firephp->log($asd);
if($asd % 2)
{
if($flag1 === 0)
{
echo ' <h4>Header '. $k .'</h4>';
$flag1 = 1;
$flag2 = 0;
$k++;
}
}
else
{
if($flag2 === 0)
{
echo ' <h4>Header '. $k. '</h4>';
$flag2 = 1;
$flag1 = 0;
$k++;
}
}
?>
You can try like
foreach($name as $parent_key => $parent_value){
echo "<h4>Header</h4><br/>";
foreach($name[$parent_key] as $key=>$value)
{
echo $name[$i][$key]."<br/>";
}
}
foreach($array as $key => $value){
$valuevalues = array();
foreach($value as $val){
if($val != "" && !isset($valuevalues[$key][$val]))
$valuevalues[$key][$val] = "different-than-previous";
if(!isset($valuevalues[$key][$val]))
$valuevalues[$key][$val] = "equal-to-first-value";
}
}

how to create html table in php

I have the following snippet of code that basically uses explode to split out these values:
<?php
$data=array();
$Inputfile = file("prod.txt");
foreach ($Inputfile as $line){
$pieces = explode(";", $line);
echo $pieces[0];
echo $pieces[1];
echo $pieces[2];
echo $pieces[3];
//print_r($line);
}
?>
Data: (prod.txt)
PREFIX=abc;PART=null;FILE=/myprojects/school/out/data/feed_abc_2010120810.gz2
PREFIX=efg;PART=sdsu;FILE=mail_efg.dat.2010120810.gz2
Can someone show me how to put this in an HTML table dynamically, like this?? Is there an easy way to do this? Thanks.
PREFIX PART FILE
abc null /myprojects/school/out/data/feed_abc_2010120810.gz2
efg sdsu mail_efg.dat.2010120810.gz2
The Clean Way
<?php
$inputfile = file("prod.txt");
$data_lines = array();
foreach ($inputfile as $line)
{
$data_lines[] = explode(";", $line);
}
//Get column headers.
$first_line = array();
foreach ($data_lines[0] as $dl)
{
$first_line[] = explode("=", $dl);
}
$headers = array();
foreach ($first_line as $fl)
{
$headers[] = $fl[0];
}
// Get row content.
$data_cells = array();
for ($i = 0; $i < count($data_lines); $i++)
{
$data_cell = array();
for ($j = 0; $j < count($headers); $j++)
{
$data_cell[$j] = substr($data_lines[$i][$j], strpos($data_lines[$i][$j], "=")+1);
}
$data_cells[$i] = $data_cell;
unset($data_cell);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HTML Table With PHP</title>
</head>
<body>
<table border="1">
<tr>
<?php foreach ($headers as $header): ?>
<th><?php echo $header; ?></th>
<?php endforeach; ?>
</tr>
<?php foreach ($data_cells as $data_cell): ?>
<tr>
<?php for ($k = 0; $k < count($headers); $k++): ?>
<td><?php echo $data_cell[$k]; ?></td>
<?php endfor; ?>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>
This should be flexible enough and won't require any hard-coded pair names:
<?php
$lines = preg_split('~\s*[\r\n]+\s*~', file_get_contents('prod.txt'));
foreach($lines as $i => $line) {
$pairs = explode(';', $line);
foreach($pairs as $pair) {
list($column, $value) = explode('=', $pair, 2);
$columns[$column] = true;
$rows[$i][$column] = $value;
}
}
$columns = array_keys($columns);
echo '<table><thead><tr>';
foreach($columns as $column) {
echo '<th>'.$column.'</th>';
}
echo '</tr></thead><tbody>';
foreach($rows as $row) {
echo '<tr>';
foreach($columns as $column) {
echo '<td>'.$row[$column].'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
?>
echo '<table><tr><td>PREFIX</td><td>Part</td>File</td></tr>';
foreach ($Inputfile as $line){
$pieces = explode(";", $line);
$count=count($pieces);
echo '<tr>';
for ($counter=0; $counter <$count; $counter++)
{
echo '<td>'.$pieces[$counter].'<td>';
}
echo '</tr>';
}
Not the prettiest solution, just an example:
echo '<table><tr><td>PREFIX</td><td>PART</td><td>FILE</td></tr>';
foreach ($Inputfile as $line)
{
$pieces = explode(';', $line);
echo sprintf(
'<tr><td>%s</td><td>%s</td><td>%s</td></tr>',
ltrim($pieces[0], 'PREFIX='),
ltrim($pieces[1], 'PART='),
ltrim($pieces[2], 'FILE=')
);
}
echo '</table>';
You've really got two problems here:
1) Parsing the information in each line into a record / associative array
2) Representing the series of these records/arrays as an HTML table.
Good code will separate these concerns somewhat.
function line2record($line) {
$recordAA = array();
$keyValuePairs = explode(';',$line);
foreach($keyValuePairs as $kvp) {
$pieces = explode('=',$kvp);
$recordAA[$pieces[0]] = $pieces[1];
}
return $recordAA;
}
function record2TR($recordAA) {
$str = implode('</td><td>',$recordAA);
return "<tr><td>$str</td></tr>";
}
After that, it's pretty much a matter of applying these two functions to each line of the file:
$Inputfile = file("prod.txt");
foreach ($Inputfile as $line)
echo record2TR(line2record($line));
To get the header row, and the table/open close markup, you might do something like this:
function record2TH($recordAA) {
$headers = array_keys($recordAA);
$str = implode('</th><th>',$headers);
return "<tr><th>$str</th></tr>";
}
and then:
$fp = fopen('prod.txt','r');
$line = fgets($fp,MAX_LINE_LENGTH); // you'd set this constant
$firstRecord = line2record($line);
echo "<table>";
echo record2TH($firstRecord);
echo record2TR($firstRecord);
while($line = fgets($fp,MAX_LINE_LENGTH))
echo record2TR(line2record($line));
echo "</table>";
This was my approach
echo '<table id="time-table" border="2"><thead><tr >';
echo '<th style="width:40%; padding: 7px;">Course Code</th>';
echo '<th style="width:30%">Course Name</th>';
echo '<th style="width:40%">Slot</th>';
for ($x = 0; $x < 5; $x++) {
echo '<tr id=row'.$x.'>';
echo '<th style="width:40%; padding: 15px;" >',$xml_data->children()[$x]->coursecode .'</th>';
echo '<th style="width:30%">',$xml_data->children()[$x]->coursename .'</th>';
echo '<th style="width:20%">',$xml_data->children()[$x]->slot .'</th>';
}
echo '</tbody></table>';
<?php
class Table
{
private $table;
private $rows;
public function __construct()
{
}
function valueof($var, $key, $default_return_value = null, $run_value_in_this_function = '')
{
$return_value = $default_return_value;
if (is_object($var)) {
if (isset($var->$key)) {
$return_value = trim($var->$key);
}
} elseif (is_array($var)) {
if (isset($var[$key])) {
$value = $var[$key];
$return_value = is_string($value) ? trim($value) : $value;
}
} else {
$return_value = $default_return_value;
}
if (!empty($return_value) && !empty($run_value_in_this_function)) {
if (function_exists($run_value_in_this_function)) {
$return_value = $run_value_in_this_function($return_value);
}
}
return $return_value;
}
function addRow($index)
{
$this->rows[$index] = [];
$this->table['rows'][$index] = [];
}
function addRows($rows)
{
$rows = (int) $rows;
for ($r = 0; $r <= $rows; ++$r) {
$this->rows[$r] = [];
$this->table['rows'][$r] = [];
}
}
function addCell($row_index, $cell_index, $cell_value)
{
$this->table['rows'][$row_index][$cell_index] = $cell_value;
}
function updateCell($row_index, $cell_index, $cell_value)
{
$this->table['rows'][$row_index][$cell_index] = $cell_value;
}
function updateColumn($column_index, $cell_values = [])
{
if (isset($this->table['rows'])) {
if (count($this->table['rows']) > 0) {
foreach ($this->table['rows'] as $row_index => $row_cells) {
$value_index = $row_index;
$new_value = $this->valueof($cell_values, $value_index);
if (!is_null($new_value)) {
$this->updateCell($row_index, $column_index, $new_value);
}
}
}
}
}
function updateRow($row_index, $row_values = [])
{
if (isset($this->table['rows'][$row_index])) {
$columns = count($this->table['rows'][$row_index]);
foreach ($this->table['rows'][$row_index] as $column_index => $column_value) {
$value_index = $column_index-1;
$new_value = $this->valueof($row_values, $value_index);
if (!is_null($new_value)) {
$this->updateCell($row_index, $column_index, $new_value);
}
}
}
}
function addHeader($row_values = [])
{
if (!empty($row_values)) {
$this->updateRow(0, $row_values);
}
}
function addColum($column_index)
{
if (isset($this->table['rows'])) {
if (count($this->table['rows']) > 0) {
foreach ($this->table['rows'] as $row_index => $row_cells) {
$this->table['rows'][$row_index][$column_index] = null;
}
}
}
}
function addColums($columns)
{
$columns = (int) $columns;
for ($col = 1; $col <= $columns; ++$col) {
if (isset($this->table['rows'])) {
if (count($this->table['rows']) > 0) {
foreach ($this->table['rows'] as $row_index => $row_cells) {
$this->table['rows'][$row_index][$col] = null;
}
}
}
}
}
public function getTable()
{
if (isset($this->table['rows']) && is_countable($this->table['rows'])) {
$table = "<table border=\"1\" width=\"50%\">";
foreach ($this->table['rows'] as $row_index => $row_cells) {
$table .= "<tr>";
if (is_countable($row_cells)) {
foreach ($row_cells as $cell_index => $cell_value) {
if (empty($cell_value)) {
$cell_value = ' ';
}
$table .= "<td class=\"data\"> {$cell_value}</td>";
}
}
$table .= "</tr>";
}
$table .= "</table>";
}
return $table;
}
function makeTable()
{
$this->addRows(5);
$this->addColums(4);
$this->addHeader(['No', 'Name', 'Unit', 'Number']);
$this->updateColumn(1, [null, '1', '2', '3', '4', '5' ]);
$this->updateColumn(2, [null, 'Cat', 'Dog', 'Horse', 'Cow', 'Hen']);
$this->updateColumn(3, [null, 'Each', 'Each', 'Each', 'Each' ]);
$this->updateColumn(3, [null, 10,20, 5, 50, 45]);
// echo '<pre>';
// print_r($this->table);
// echo '</pre>';
$table = $this->getTable();
return $table;
}
}
$table = new Table();
print $table->makeTable();

Categories