Here is what my code prints:
Even numbers: 2 4 6
Here is my PHP code:
$names = file('file.txt');
echo "Text: ";
foreach($names as $name)
{
echo $name . "</br>";
}
echo "Even numbers: ";
foreach ($names as $name) {
$name = count_chars( $name, 3);
for($i=0; $i<strlen($name);$i++) {
if (is_numeric($name[$i]) && $name[$i]%2==0)
{
echo $name[$i];
}
}
echo "<br>";
}
?>
Could someone tell me how should I count all of these values into the new line (I need to get an answer 3) and get those values sum (I need to get 12)? I know I have to use count and sum functions, i don't know exactly where. Thanks for any help. All the answer should look like this:
Even numbers: 2 4 6
Even numbers are: 3
Even numbers sum are: 2 + 4 + 6 = 12
I don't really understand what your question.
But I think array_sum is what you are looking for. (https://secure.php.net/manual/en/function.array-sum.php)
Below is my code for your reference:
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach($array as $key => $value) {
if (empty($value%2)) {
$even[] = $value;
} else {
$odd[] = $value;
}
}
echo 'Even numbers: '.implode(' ', $even).'<br>';
echo 'Odd numbers: '.implode(' ', $odd).'<br>';
echo 'Even numbers sum are: '.implode(' + ', $even).' = '.array_sum($even);
Try this :
$names = file('file.txt');
echo "Text: ";
foreach($names as $name)
{
echo $name . "</br>";
}
echo "Even numbers: ";
foreach ($names as $name) {
$count = 0
$evens = [];
$name = count_chars($name, 3);
for($i=0; $i<strlen($name);$i++) {
if (is_numeric($name[$i]) && $name[$i]%2==0)
{
$count++;
$evens[] = $name[$i];
echo $name[$i];
}
}
echo "<br>";
}
echo "Even numbers Are: " . $count;
$i=0;
foreach($evens as $e){
$i++;
if($i == count($evens)){
$evens_string .= $e . '=' ;
} else {
$evens_string .= $e . '+' ;
}
}
$even_string .= array_sum($evens);
echo "Even numbers sum are: " . $even_string;
Hope this gives you the idea! I have not tested the code.
Related
I am confused to count these words,
I've some data like this :
web = 1
sistem=1
web=1
sistem=1
web=1
sistem=1
sistem=0
sistem=0
web=0
sistem=0
web=0
sistem=0
web=0
web=0
I want to make result like this :
web = 3
sistem = 3
I'm using array_count_values(), but this result is not good
Array ( [web=1] => 3 [sistem=1] => 3 [sistem=0] => 4 [web=0] => 4 )
My code like this :
foreach ($g as $key => $kata) {
if (strpos($cleanAbstrak, $kata)) {
echo $kata . $ada . "<br>";
$p[] = $kata . "=" . $ada;
// print_r($p);
echo "<br><br>";
} else {
echo $kata, $tidak . "<br>";
$q[] = $kata . "=" . $tidak;
// $m = explode(" ", $q);
// print_r($q);
// echo $q . '<br>';
echo "<br><br>";
}
}
$s = array_merge($p, $q);
echo "<br><br>";
print_r($s);
echo "<br>";
$f = array_count_values($s);
// print_r($f);
echo "<br><br>";
thank you very much if you are willing to help me
RESULT THIS CODE
Another simple way is use a counter like that:
$web=0;
$sistem=0;
foreach ($g as $key => $kata) {
if (strpos($cleanAbstrak, $kata)) {
$sistem=$sistem + $ada;
} else {
$web=$web+$tidak
}
}
echo 'web='.$web.'<br> sistem='.$sistem;
First, you need to separate word and value.
Second, you need to check the value : if it's zero you let it go (can't hold it back anymore). Else you count the value ; if it's written, i suppose it can be greater than 1 ; if it's not, it should be "word", or nothing (which would greatly facilitate counting).
Something like
<?php
$tab = [
'web=1',
'sistem=1',
'web=1',
'sistem=1',
'web=1',
'sistem=1',
'sistem=0',
'sistem=0',
'web=0',
'sistem=0',
'web=0',
'sistem=0',
'web=0',
'web=0',
];
$tab_clean = [];
foreach($tab as $item) {
preg_match('/([a-z]+)=([\d]+)/', $item, $matches);
//print_r($matches);
$word = $matches[1];
$number = $matches[2];
for($i = 0; $i < $number; $i++) {
$tab_clean[] = $word;
}
}
$tab_count = array_count_values($tab_clean);
print_r($tab_count);
?>
This function is supposed to echo all singles and doubles numbers. (eg. 01 - 01 02).
I am trying to place a title before each 'category' using the code below and it is not working properly.
It should be something like this
SINGLES
01,02,03
DOUBLES
01 02, 03 04, 05 06
Can you help me fix this? Thanks!
function check_stats($todas){
$arrlength = count($todas);
for($x = 0; $x < $arrlength; $x++) {
$arrlength2 = count($todas[$x]);
if($arrlength2==1){
echo 'single'.'</br></br>';
list($a) = explode(" ", implode(" ", $todas[$x]));
echo $a; echo '</br>';
}
if($arrlength2==2){
echo 'double'.'</br></br>';
list($a,$b) = explode(" ", implode(" ", $todas[$x]));
echo $a.' '.$b; echo '</br>';
}
} //for
} //function
You are trying to separate singles and doubles. And you want to print them separately. You can't print them separately while you haven't detected them all. Then you need to detect all categories and after that you can print them separately. To do this you should save categories on detection and after detection print saved categories.
function check_stats($todas){
$singles = array(); // an array to save single numbers
$doubles = array(); // an array so save doubles
foreach ($todas as $toda) { // cleaner and beautifier than for
if (count($toda) == 1) { // direct compare without extra $arrlength2
$singles[] = $toda[0]; // will push $toda[0] to $singles array
} else if (count($toda) == 2) { // when put else compares less
$doubles[] = $toda[0] . ' ' . $toda[1];
}
}
// then you can do whatever with $singles and $doubles
echo 'SINGLES' . PHP_EOL;
foreach ($singles as $single) {
echo $single . PHP_EOL;
}
echo 'DOUBLES' . PHP_EOL;
foreach ($doubles as $double) {
echo $double . PHP_EOL;
}
}
Edit #1:
If there were more than 2 kind of variables, then you can keep them in an array.
function check_stats($todas){
$result_array = array();
foreach ($todas as $toda) {
$result_array[count($toda)] = implode(' ', $toda);
// the above code will save each single or double or triple or etc
// in an index in their size
}
return $result_array; // better return it and use out of function
}
$result = check_stats($todas);
// now print them
foreach ($todas as $key => $toda) {
echo $key . PHP_EOL; // print count (that is index)
foreach ($toda as $t) {
echo $t . PHP_EOL;
}
}
Is it possible to display an array as a sentence? So between each of the values there would be ", " except before the last value there would be " and ".
I have taken this little piece of code to use within an example:
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
This works great for three values but I need it to work for between 1 and 15 values.
Thanks
$carsCount = count($cars);
if ($carsCount == 1) {
$sentence = $cars[0] . '.';
} else {
$partial = array_slice($cars, 0, $carsCount-1);
$sentence = implode(', ', $partial) . ' and ' . $cars[$carsCount-1];
}
echo $sentence;
$array = array("Volvo", "BMW", "Toyota");
$sentence = '';
foreach($array as $k => $v) {
if (count($array) == 1) {
$sentence = $v;
break;
}
else if ($k == count($array)-1) {
$sentence .= 'and ' . $v;
}
else {
$sentence .= $v . ', ';
}
}
echo $sentence;
Above returns the following: Volvo, BMW, and Toyota
There is another way [shorter], [faster].
$cars = array("Volvo", "BMW", "Toyota", "Fiat");
if (count($cars) > 1) {
$lastVal = array_pop($cars);
echo implode(",", $cars)." and ".$lastVal;
} else {
echo $cars[0];
}
I have a multi-dimension array in php like this
$shop = array(
array("name","point","number"),
array('Ranjit', 1.25 , 15),
array('Pitabas', 0.75 , 25),
array('Khela', 1.15 , 7)
);
Now I have to show the output like this
name-> ranjit
Point-> 1.25
number->15
name->Pitabas
Point->0.75
number->25
name->Khela
Point->1.15
number->7
I am trying for loop, but I could get the result in nested forloop. Please help me to get the answer.
My solution:
$headings = array_shift($shop);
foreach ($shop as $item) {
foreach ($item as $key => $value) {
echo $headings[$key], '=>', $value;
}
}
Here's a simple loop: Observe that we skip the first element of the outer array, which is deemed to contain the headers:
for ($i = 1; $i != count($shop); ++$i)
{
print $shop[0][0] . ": ". $shop[$i][0] . "\n";
print $shop[0][1] . ": ". $shop[$i][1] . "\n";
print $shop[0][2] . ": ". $shop[$i][2] . "\n";
}
You know the first row will be the titles, so store them separately:
$titles = $shop[0];
That will give you
$titles = array('name', 'point', 'number');
Then loop through your array:
foreach ($shop as $index => $row) {
if ($index == 0)
continue;
foreach($row as $column => $item) {
echo $titles[$column] . " -> " . $item . "<br />";
}
}
This should give the desired output:
for($x = 1, $lim = sizeof($shop); $x < $lim; $x++)
{
echo $shop[0][0]."->".$shop[$x][0]."<br>";
echo $shop[0][1]."->".$shop[$x][1]."<br>";
echo $shop[0][2]."->".$shop[$x][2]."<br>";
}
<?php
$arr = range(1,rand(40,120)); ?>
<table>
<?php
foreach ($arr as &$value) {
echo '<tr><td>' . $value . '</td></tr>';
} ?>
</table>
This generate for me for example:
1
2
3
...
111
all in one columns. How can i make - when in first column are 25 rows then create new column, etc. For example:
1 26 51
2 27 ...
3
..
25 50
How can i make it?
I can use DIV instead of table.
<?php
$arr = range(1,rand(40,120));
?>
<div style="width:40px; float:left;">
<?php
foreach ($arr as $value) {
echo $value . '<br />';
if ($value % 25 == 0) {
echo '</div><div style="width:40px; float:left;">';
}
}
?>
Vertically sorted columns of that sort (no pun intended) are a serious pain in html, since this arragement is a "top->bottom, left->right", while HTML tables by their nature are "left->right, top->bottom" instead.
To get around it, you have to do some offset math on the array indexes, so you can output by rows:
$arr = range(1,rand(40,120));
$rows = ceil(count($arr) / 3); // assuming 3 columns
for ($i = 0; $i < $rows; $i++) {
echo <<<EOL
<tr>
<td>{$arr[$i]}</td> 1, 2, 3, etc...
<td>{$arr[$i+rows]}</td> 11, 12, 13, etc...
<td>{$arr[$i+(2*$rows)]}</td> 21, 22, 23, etc...
</tr>
EOL;
}
This code probably won't work as is, but should give you the basic idea.
EDITED
<?php
$rows = 25;
$arr = range(1, rand(40, 120));
$arr = array_merge($arr, array_fill(0, $rows - (count($arr) % $rows), null));
$cols = ceil(count($arr) / $rows);
$render = array();
echo '<table>' . "\n";
foreach ($arr as $i => $value) {
$render[$i % $rows][] = $value;
if (count($render[$i % $rows]) == $cols) {
echo ' <tr>' . "\n" . ' <td>' . implode('</td>' . "\n" . ' <td>', $render[$i % $rows]) . '</td>' . "\n" . ' </tr>' . "\n";
}
}
echo '</table>' . "\n";
?>