php count even numbers in an array - php

So I am trying to learn php, and the code for finding even numbers doesn't output anything, but I can't seem to find the error, can anybody find where I have made my stupid mistake? Here is the code:
<?php
/*this sets the array up with the data*/
$myarray = array(1,2,3,4,5,6,7,8,9,10);
/* this is the count to get the total number from my array */
$total = count($myarray);
?>
<h1>Display all even numbers</h1>
<ul>
<?php for ($i=1; $i < total; $i += 2): ?>
<li>The array element value is <?php echo $myarray[$i]; ?>. </li>
<?php endfor; ?>
</ul>
Thanks and if nobody wants to post an answer I understand new questions are frustrating.
thanks

Your code isn't finding even numbers. You're identifying their positions in the array, and printing values only for those indexes. Look at this php snippet.
<?php
$myarray = array(1,2,3,4,5,6,7,8,9,10);
// Array indexes start at 0, not 1.
for ($i = 0; $i < count($myarray); $i++) {
echo "Index ", $i, ", value ", $myarray[$i], ": ";
// A value is even if there's no remainder when you divide it by 2.
if ($myarray[$i] % 2 == 0) {
echo "even\n";
}
else {
echo "odd\n";
}
}
?>
Put that in a file, and run it through php. You should see this.
Index 0, value 1: odd
Index 1, value 2: even
Index 2, value 3: odd
Index 3, value 4: even
Index 4, value 5: odd
Index 5, value 6: even
Index 6, value 7: odd
Index 7, value 8: even
Index 8, value 9: odd
Index 9, value 10: even
This shorter version will print only the even values.
<?php
$myarray = array(1,2,3,4,5,6,7,8,9,10);
for ($i=0; $i < count($myarray); $i++) {
if ($myarray[$i] % 2 == 0) {
echo "Index ", $i, ", value ", $myarray[$i], "\n";
}
}
?>
Index 1, value 2
Index 3, value 4
Index 5, value 6
Index 7, value 8
Index 9, value 10

You're missing the $ variable creator in your for loop for total:
<?php for ($i=1; $i < $total; $i += 2): ?>

This code fits your problem.
<?php
$myarray = array(1,2,3,4,5,6,7,8,9,10);
$total = count($myarray);
echo "<h1>Display all even numbers</h1>";
echo "<ul>";
foreach($myarray as $rw)
{
if(($rw%2) == 0 ){
echo "<li>".$rw."</li>";
}
}
echo "</ul>";
?>
The modulus operator % is the best way to get the odd or even numbers in an array.

printing a even number in php. there $ais 20 when you run this code the out put is 2, 4, 6, 8, 10, 12, 14, 16, 18, 20,
$a = 20
for ($i=0; $i < $a; $i += 2)
{
echo "</n><br>".$i;
}
Out put like this
2
4
6
8
10
12
14
16
18
20

Related

How to deduct specific array "values from another values" in PHP?

I have an array like this:
$datas = array(54,12,61,98,88,
92,45,22,13,36);
I want to write a loop which can deduct values of an array like below and show it with echo:
$datas[5]-$datas[0] for this line the result will be 92-54 "38"
$datas[6]-$datas[1] for this line the result will be 45-12 "33"
$datas[7]-$datas[2] ... "-39"
my codes are:
<?php
$smonth1= 0;
$emonth1=5;
for ($i = 5; $i > 0; $i-- ) {
$result = array_diff($datas[$emonth1], $datas[$smonth1]);
echo (implode ($result))."<br/>" ;
$smonth1++ ;
$emonth1++;
}
?>
but I couldn't get the result I don't know why. I am fresh in php. Can you help me??
Assuming the input array always has an even number of values in it (which I think is the only way this scenario could logically work), then you can simply count how many items are in the array, and then loop through it, taking the nth item and subtracting it from the n+(total / 2)th item.
$data = array(54,12,61,98,88,
92,45,22,13,36);
$halfway = count($data)/ 2;
for ($i = 0; $i < $halfway; $i++)
{
$j = $i + $halfway;
echo $data[$j] - $data[$i].PHP_EOL;
}
Demo: https://3v4l.org/ictDT
Basically, you want something like this
<?php
$data = [
54, 12, 61, 98, 88,
92, 45, 22, 13, 36
];
$offset = 5;
for ($i = 0; $i + $offset < count($data); $i++) {
echo $data[$i + $offset] - $data[$i];
echo "\n"; // or <br/> if you run it in browser
}

How to efficiently sum paired array elements and avoid offset errors in case of pairless array?

Pair every two arrays is the task – store it, print it and repeat it until it becomes one value.
input : 1, 2, 3, 4, 5, 6, 8, 9, 9
output: 3 7 11 17 9
10 28 9
38 9
47
My code is working fine in this scenario. Somehow I managed to add 0 at the end for pairless elements. But my main focus is how can I make the logic even more clearer to avoid grumpy offset errors?.
My code:
function sumForTwos($arr)
{
if(count($arr) == 1){
exit;
}
else {
$sum = [];
for ($i = 0; $i < count($arr) -1; $i++)
{
//logic to add last array for odd count to avoid offset error
if(count($arr) % 2 == 1){ $arr[count($arr)] = 0; }
//logic to pair arrays
if($i != 0) { $i++; }
$sum = $arr[$i] + $arr[$i + 1];
$total[] = $sum;
echo $sum . " ";
}
echo "<br>";
$arr = $total;
//Recursion function
sumForTwos($arr);
}
}
sumForTwos([1, 2, 3, 4, 5, 6, 8, 9, 9]);
You can adopt an iterative approach and look at this as processing each level of values with every next level have 1 value less from total values. In other words, you can look at this as a breadth first search going level by level. Hence, you can use a queue data structure processing each level one at a time.
You can use PHP's SplQueue class to implement this. Note that we can advantage of this class as it acts as a double-ended queue with the help of below 4 operations:
enqueue - Enqueues value at the end of the queue.
dequeue - Dequeues value from the top of the queue.
push - Pushes value at the end of the doubly linked list(here, queue is implemented as doubly linked list).
pop - Pops a node from the end of the doubly linked list.
Most certainly, all the above 4 operations can be done in O(1) time.
Algorithm:
Add all array elements to queue.
We will loop till the queue size is greater than 1.
Now, if queue level size is odd, pop the last one and keep it in buffer(in a variable).
Add all pairwise elements by dequeueing 2 at a time and enqueue their addition for next level.
After level iteration, add the last element back if the previous level size was odd.
Print those added elements and echo new lines for each level accordingly.
Snippet:
<?php
function sumForTwos($arr){
if(count($arr) == 1){
echo $arr[0];
return;
}
$queue = new SplQueue();
foreach($arr as $val){
$queue->enqueue($val); // add elements to queue
}
while($queue->count() > 1){
$size = $queue->count();
$last = false;
if($size % 2 == 1){
$last = $queue->pop(); // pop the last odd element from the queue to make queue size even
$size--;
}
for($i = 0; $i < $size; $i += 2){
$first = $queue->dequeue();
$second = $queue->dequeue();
echo $first + $second," ";
$queue->enqueue($first + $second);
}
if($last !== false){// again add the last odd one out element if it exists
echo $last; // echo it too
$queue->push($last);
}
echo PHP_EOL;// new line
}
}
sumForTwos([1, 2, 3, 4, 5, 6, 8, 9, 9]);
Demo: http://sandbox.onlinephpfunctions.com/code/5b9f6d4c9291693ac7cf204af42d1f0ed852bdf9
Does this do what you want?
function pairBySums($inputArray)
{
if (sizeof($inputArray) % 2 == 1) {
$lastEntry = array_pop($inputArray); //$inputArray now has even number of elements
}
$answer = [];
for ($ii = 0; $ii < sizeof($inputArray) / 2; $ii++) {
$firstIndexOfPair = $ii * 2; // 0 maps to 0, 1 maps to 2, 3 maps to 4 etc
$secondIndexOfPair = $firstIndexOfPair + 1; // 0 maps to 1, 1 maps to 3, 2 maps to 5 etc
$answer[$ii] = $inputArray[$firstIndexOfPair] + $inputArray[$secondIndexOfPair];
}
if (isset($lastEntry)) {
array_push($answer, $lastEntry);
}
echo implode(' ', $answer) . "<br>";
if (sizeof($answer) > 1) {
pairBySums($answer);
}
}
The algorithm makes sure it operates on an even array and then appends the odd entry back on the array if there is one.
$input = [1, 2, 3, 4, 5, 6, 8, 9, 9];
pairBySums($input);
produces:
3 7 11 17 9
10 28 9
38 9
47
With an even number of items,
$input = [1, 2, 3, 4, 5, 6, 8, 9];
pairBySums($input);
produces:
3 7 11 17
10 28
38

I want to get elements from array in order: three, four, three, four and so on

I want to get elements from an array like this: get first three element, then four elements, then again three elements, and again four, and so on in a loop.
For example:
0 1 2
3 4 5 6
7 8 9
10 11 12 13
and so on....
I tried something like this:
foreach($items as $key => $item) {
if($key <= 2) {
echo 'test';
}
if($key > 2 && $key < 6) {
echo 'other test';
}
if($key > 6 && $key < 9) {
echo 'test';
}
}
However, I don't want to use if() like these, because I don't know how many items will be in the array: it comes from a database.
I think, I need something like array_chunk($items, 3) but for size parameter I need 3 and 4 in loop
Could be like this you can make another array of specifying the number of elements you want in each iteration.
<?php
$number_of_elements = [3,4,3,4];
$your_array = ['a', 'b','c','d','e'];
foreach($number_of_elements as $number){
for($i = 0; $i<=$number; $i++){
$result = $your_array[$i];
print_r($result);
}
print_r('<br>');
}
In JavaScript you can solve your problem using a for loop and the built in slice function of the array.
const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
let offset = 0;
for(let i = 0; i < array.length;){
offset = offset === 3 ? 4 : 3;
const subArray = array.slice(i, i + offset);
console.log(subArray);
i += offset;
}

Getting nth-child with an offset in PHP with modulus

When iterating through a loop, I've used the modulus operator in an if statement to obtain nth results pretty easily like this:
// Get 5th item in series
if ($variable->array_item % 5 == 0) {
echo $variable->array_item;
}
How do you do get the 5th item in a series with an offset of 3 (ie, 3,8,13,18,23,etc.)?
I've seen a couple of methods but I'm looking for a canonical answer and I really don't see one on S.O. right now.
Your code specifically requests numbers that are evenly divisible by 5, whereas what you want are numbers 3, 8, 13, 18, 23, etc. This is easy enough to do using almost identical code to what you have:
// set up some test data
$testArray = [];
for ($i = 1; $i <= 30; ++$i) {
$testArray[$i] = "Testing {$i}";
}
// here's where the actual work happens
foreach ($testArray as $key => $value) {
if ($key % 5 == 3) { // <-- note 3, not 0
echo "Found $value\n";
}
}
$iterator = 0;
$step = 3;
while($iterator < count($collection))
{
echo $collection[$iterator]
$iterator += $step
}

How to increment a number by 2 in a PHP For Loop [duplicate]

This question already has answers here:
PHP while loop add by 2
(3 answers)
Closed 1 year ago.
The following is a simplified version of my code:
<?php for($n=1; $n<=8; $n++): ?>
<p><?php echo $n; ?></p>
<p><?php echo $n; ?></p>
<?php endfor; ?>
I want the loop to run 8 times and I want the number in the first paragraph to increment by 1 with each loop, e.g.
1, 2, 3, 4, 5, 6, 7, 8 (this is obviously simple)
However, I want the number in the second paragraph to increment by 2 with each loop, e.g...
1, 3, 5, 7, 9, 11, 13, 15
I can't figure out how to make the number in the second paragraph increment by 2 with each loop. If I change it to $n++ then it increments by 2, but it then makes the loop run only 4 times instead of 8.
Any help would be much appreciated. Thanks!
You should do it like this:
for ($i=1; $i <=10; $i+=2)
{
echo $i.'<br>';
}
"+=" you can increase your variable as much or less you want.
"$i+=5" or "$i+=.5"
<?php
for ($n = 0; $n <= 7; $n++) {
echo '<p>'.($n + 1).'</p>';
echo '<p>'.($n * 2 + 1).'</p>';
}
?>
First paragraph:
1, 2, 3, 4, 5, 6, 7, 8
Second paragraph:
1, 3, 5, 7, 9, 11, 13, 15
You should use other variable:
$m=0;
for($n=1; $n<=8; $n++):
$n = $n + $m;
$m++;
echo '<p>'. $n .'</p>';
endfor;
Simple solution
<?php
$x = 1;
for($x = 1; $x < 8; $x++) {
$x = $x + 1;
echo $x;
};
?>
Another simple solution with +=:
$y = 1;
for ($x = $y; $x <= 15; $y++) {
printf("The number of first paragraph is: $y <br>");
printf("The number of second paragraph is: $x+=2 <br>");
}
<?php
$x = 1;
for($x = 1; $x < 8; $x++) {
$x = $x + 2;
echo $x;
};
?>

Categories