Display even & odd numbers - php

I am trying loop through an array of random numbers if the the number is dividable by two then it's even and I then want to assign this to an array $even[], and if odd then assign it to the odd array. I have managed to display the results without using an array but for the sake of this I want to put them into their own array. However I can't seem to get this result I'm after all I get is this error: message Array to string conversion.
<?php
$numbers = array();
for ($i=0; $i<=1000; $i++) {
$numbers[]=mt_rand(1,1000);
if ($i % 2 == 0){
$even[]=$i;
} else {
$odd[]=$i;
}
}
echo $even;
echo $odd;
?>

Try this to echo the results.
foreach ($even as $evens){
echo $evens . '<br/>';
}

define $odd and $even as a array
$even = array();
$odd = array();
check if($i%2 == 0)
{
$even[] = $i;
}
else
{
$odd = $i;
}
var_dump($even);
var_dump($odd);

Related

I have 6 values in array but when I execute, only 4 values are showed. why?

I have 6 values in array $arr1 but when I execute the code, only 4 values are shown, why?
The code finds that the maximum value is 526, but where I use echo to list the whole array the 526-valued array is not shown.
Here is the code:
<?php
$arr1[0][ ]=110;
$arr1[0][ ]=20;
$arr1[0][ ]=526;
$arr1[1][ ]=105;
$arr1[1][ ]=56;
$arr1[1][ ]=96;
echo "The given array is : <br>";
for($i=0;$i=count($arr1);$i++)
{
for($j=0;$j=count($arr1);$j++)
{
Echo "\$arr1[$i][$j] =",$arr1[$i][$j],"<br>";
}
}
$b=0;
foreach($arr1 as $val)
{
foreach($val as $key=>$val1)
{
$b=$val1;
}
}
Echo "The maximum value in the array is =",$b;
?>
There are a few issues with your code example.
The array $arr1 has 2 entries with keys 0 and 1 so if you loop 2 times 2 values, you get 4 values instead of 6.
Then per key, there are 3 entries, so for the second loop you have to use count($arr1[$i]) using [$i] to count the entries for that key.
In the loops, you are setting the value of $i to the count causing an infinite loop $i=count($arr1) while you have to use a < sign instead.
In the second part finding the largest value, you have to first check if the new value is greater than the current value, or else you will always have the last value.
$arr1[0][] = 110;
$arr1[0][] = 20;
$arr1[0][] = 526;
$arr1[1][] = 105;
$arr1[1][] = 56;
$arr1[1][] = 96;
echo "The given array is : <br>";
for ($i = 0; $i < count($arr1); $i++) {
for ($j = 0; $j < count($arr1[$i]); $j++) {
echo "\$arr1[$i][$j] =", $arr1[$i][$j], "<br>";
}
}
$b = 0;
foreach ($arr1 as $val) {
foreach ($val as $key => $val1) {
if ($val1 > $b)
$b = $val1;
}
}
echo "The maximum value in the array is =", $b;
Output
The given array is :
$arr1[0][0] =110
$arr1[0][1] =20
$arr1[0][2] =526
$arr1[1][0] =105
$arr1[1][1] =56
$arr1[1][2] =96
The maximum value in the array is =526
See a Php demo
As #Nick points out, you could also compute the max in the nested for loops directly:
$b = 0;
echo "The given array is :" . PHP_EOL;
for ($i = 0; $i < count($arr1); $i++) {
for ($j = 0; $j < count($arr1[$i]); $j++) {
if ($arr1[$i][$j] > $b) $b = $arr1[$i][$j];
echo "\$arr1[$i][$j] =", $arr1[$i][$j] . PHP_EOL;
}
}
Php demo
You can flatten the array by using splat operator then use max.
echo max(array_merge(...$arr1));
If you want you can use implode to print the values
echo implode(' ',array_merge(...$arr1));
DEMO :- https://3v4l.org/0ZamG
Please use this code. I hope it will works for you.
$arr1[0][ ]=110;
$arr1[0][ ]=20;
$arr1[0][ ]=526;
$arr1[1][ ]=105;
$arr1[1][ ]=56;
$arr1[1][ ]=96;
echo "The given array is : <br>";
for($i=0;$i<count($arr1);$i++)
{
for($j=0;$j<count($arr1);$j++)
{
echo "$arr1[$i][$j] =",$arr1[$i][$j],"<br>";
}
}
$b=0;
sort($arr1);
foreach($arr1 as $val)
{
foreach($val as $key=>$val1)
{
$b=$val1;
}
}
echo "The maximum value in the array is =",$b;

How to find the last item of an array?

I have an array with three objects:
Ob1
Ob2
Ob3
I tried the following:
$args = array('child_of' => 184);
$categories = get_the_category($post->ID, $args);
$i = 0;
$len = count($categories);
foreach($categories as $cat) {
if ($i == 0) {
echo '<li><h2>'.$cat->name.', </h2></li>';
} else if ($i == $len - 2) {
echo '<li><h2>'.$cat->name.'</h2></li>';
}
$i++;
}
But I get
Ob1, Ob2
Basically if it is the last item I don't want the comma but I am not sure what is wrong with that code and why it is showing only two values.
If I do:
var_dump($len);
It gives me int(3)
You only want your $i conditional logic to apply to $len - 1.
The easiest way to do this is to simply swap the conditionals around and offset it by one:
foreach($categories as $cat) {
if ($i == $len - 1) {
echo '<li><h2>'.$cat->name.'</h2></li>';
} else {
echo '<li><h2>'.$cat->name.', </h2></li>';
}
$i++;
}

php loop through array to find X consecutive numbers

I have some code that finds 3 consecutive numbers from an array and outputs them.
What I would like it to do now is be able to tell it how many numbers to find. I did think about putting a for loop inside the outside for loop but i don't see it working properly.
How can i get this iteration to run X times until X is met?
if(isset($arr[$i+1]))
if($arr[$i]+1==$arr[$i+1])
echo 'I found it:',$arr[$i],'|',$arr[$i+1],'|',$arr[$i+2],'|',$arr[$i+3],'<br>';
exit;
This is what i have so far
for($i=0; $i < sizeof($arr); $i++) {
if(isset($arr[$i+1]))
if($arr[$i]+1==$arr[$i+1])
{
if(isset($arr[$i+2]))
if($arr[$i]+2==$arr[$i+2])
{
if(isset($arr[$i+3]))
if($arr[$i]+3==$arr[$i+3])
{
echo 'I found it:',$arr[$i],'|',$arr[$i+1],'|',$arr[$i+2],'|',$arr[$i+3],'<br>';
exit;
}//if3
}//if 2
}//if 1
}
Instead of looking forward repeatedly, you could just loop through the array, comparing the current value to the previous value to see if the values are consecutive, while keeping track of the current consecutive count. Consecutive numbers should be appended to an array, and non-consecutive numbers should reinitialize the array. When you reach the desired count of consecutive numbers, you can return the result.
function find_consecutive($array, $count) {
$consecutive = array();
$previous = null;
foreach ($array as $value) {
if ($previous !== null && $value == $previous + 1) {
$consecutive[] = $value;
if ($found == $count) {
return "I found it: " . implode("|", $consecutive) . "<br>";
}
} else {
$consecutive = array($value);
$found = 1;
}
$previous = $value;
$found++;
}
}

Issue with custom script to sort Arrays ascending and descending order

I have an issue to deal with here (a logical error in my code 99%). I just can't seem to find the way to fix it, but I bet one of you will find the problem in no time!
I have to create a function which sorts array passed to it in asc or desc order, but can't use any array sorting functions !
I've been struggling with loops until now and I finally want to ask help from other devs ( you ).
Currently only code for ascending is worked on, descending will be no problem I assume once I do this one. It kinda of does sort values up to some point, but then stops ( it stops if the next smallest value is at the end of the passed array ). What could I do to prevent this and make it sort the whole array and it's elements?
Here is the code so far.
<?php
function order_array($array,$mode = 'ascending') {
$length = count($array);
if($mode == 'descending') {
return $array;
} else {
$sorted_array = array();
$used_indexes = array();
for($i = 0; $i < $length; $i++) {
$smallest = true;
echo $array[$i] . '<br/>';
for($y = 0; $y < $length; $y++) {
//echo $array[$i] . ' > ' . $array[$y] . '<br/>';
// if at ANY time during checking element vs other ones in his array, he is BIGGER than that element
// set smallest to false
if(!in_array($y,$used_indexes)) {
if($array[$i] > $array[$y]) {
$smallest = false;
break;
}
}
}
if($smallest) {
$sorted_array[] = $array[$i];
$used_indexes[] = $i;
}
}
return $sorted_array;
}
}
$array_to_sort = array(1, 3, 100, 99, 33, 20);
$sorted_array = order_array($array_to_sort);
print_r($sorted_array);
?>
I've solved the issue myself by doing it completely different. Now it sorts correctly all the elements of the passed in array. The logical issue I had was of using for() loop. The for() loop ran only a set ( length of passed array ) number of times, while we need it to loop more than that, because we will need to loop all the way untill we have a new sorted array in ascending order. Here is the code that will work
function order_array($array,$mode = 'ascending') {
if($mode == 'descending') {
// for() wont work here, since it will only loop an array length of times, when we would need it
// to loop more than that.
while(count($array)){
$value = MAX($array);
$key = array_search($value, $array);
if ($key !== false) {
unset($array[$key]);
}
$sorted[] = $value;
}
return $sorted;
} else {
// for() wont work here, since it will only loop an array length of times, when we would need it
// to loop more than that.
while(count($array)){
$value = MIN($array);
$key = array_search($value, $array);
if ($key !== false) {
unset($array[$key]);
}
$sorted[] = $value;
}
return $sorted;
}
}
function order_array($array,$mode = 'ascending') {
$length = count($array);
$sorted_array = array();
$used_indexes = array();
for($i = 0; $i < $length; $i++) {
$smallest = true;
echo $array[$i] . '<br/>';
for($y = 0; $y < $length; $y++) {
//echo $array[$i] . ' > ' . $array[$y] . '<br/>';
// if at ANY time during checking element vs other ones in his array, he is BIGGER than that element
// set smallest to false
if(!in_array($y,$used_indexes)) {
if($array[$i] > $array[$y]) {
$smallest = false;
break;
}
}
}
if($smallest) {
$sorted_array[] = $array[$i];
$used_indexes[] = $i;
}
if($mode == 'descending') {
return array_reverse($sorted_array);
}
return $sorted_array;
}
}

PHP Loop: Every 4 Iterations Starting From the 2nd

I have an array that can have any number of items inside it, and I need to grab the values from them at a certain pattern.
It's quite hard to explain my exact problem, but here is the kind of pattern I need to grab the values:
No
Yes
No
No
No
Yes
No
No
No
Yes
No
No
I have the following foreach() loop which is similar to what I need:
$count = 1;
foreach($_POST['input_7'] as $val) {
if ($count % 2 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}
However, this will only pick up on the array items that are 'even', not in the kind of pattern that I need exactly.
Is it possible for me to amend my loop to match that what I need?
You can do this much simpler with a for loop where you set the start to 1 (the second value) and add 4 after each iteration:
for ($i = 1; $i < count($_POST['input_7']); $i += 4) {
echo $_POST['input_7'][$i] . '<br />';
}
Example:
<?php
$array = array(
'foo1', 'foo2', 'foo3', 'foo4', 'foo5',
'foo6', 'foo7', 'foo8', 'foo9', 'foo10',
'foo11', 'foo12', 'foo13', 'foo14', 'foo15'
);
for ($i = 1; $i < count($array); $i += 4) {
echo $array[$i] . '<br />';
}
?>
Output:
foo2foo6foo10foo14
DEMO
Try this:
$count = 3;
foreach($_POST['input_7'] as $val) {
if ($count % 4 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}

Categories