For-each loop, larger than 20 into another array - php

I'm stuck on this exercise that I can't seem to get for the life of me.
$numbers2 = [21, 5, 4, 6, 76, 2, 18, 85, 55, 1];
foreach ($numbers2 as &$value) {
$largeNumbers[] = $value > 20;
}
That's the code I have so far. What I am trying to do here is use a for-each loop to add all the numbers that are larger than 20 into another Array, which I have named $largeNumbers. The code I have inserted above seems to be printing out true and false values, which is not what I was going for. I'd really appreciate it someone could tell me what I'm possibly doing wrong or even show me a better way. I have to use a for-each loop.

For each item, you are checking if it's larger than 20, which results in a boolean value (it either is or is not), and you then store this value to the result array. Instead, you could use an if statement` to only take the elements that answer the condition:
foreach ($numbers2 as &$value) {
if ($value > 20) {
$largeNumbers[] = $value;
}
}

<?php
$nums = [21, 5, 4, 6, 76, 2, 18, 85, 55, 1];
$less_than_or_equal_to_20 = [];
foreach($nums as $v)
if($v <= 20)
$less_than_or_equal_to_20[] = $v;
$out = array_diff($nums, $less_than_or_equal_to_20);
var_export($out);
Output:
array ( 0 => 21, 4 => 76, 7 => 85, 8 => 55, )

<?php
$nums = [21, 5, 4, 6, 76, 2, 18, 85, 55, 1];
foreach([$nums] as $v)
$out = array_filter($v, function($v) {
return $v > 20;
});
var_export($out);
Output:
array ( 0 => 21, 4 => 76, 7 => 85, 8 => 55, )

Related

Creating a list and indexing

Given a two list. Create a third list by picking an odd-index element from the first list and even index elements from the second.
For Example:
listOne = [3, 6, 9, 12, 15, 18, 21]
listTwo = [4, 8, 12, 16, 20, 24, 28]
Expected Output:
Printing Final third list
[6, 12, 18, 4, 12, 20, 28]
I think, it will be helpful for you.
<?php
$listOne = [3, 6, 9, 12, 15, 18, 21];
$listTwo = [4, 8, 12, 16, 20, 24, 28];
$NlistOne=[];
$NlistTwo=[];
//odd-index positions from list one [6, 12, 18]
foreach ($listOne as $key => $value) {
if($key%2==1){
array_push($NlistOne, $value);
}
}
//even-index positions from list two [4, 12, 20, 28]
foreach ($listTwo as $key => $value) {
if($key%2==0){
array_push($NlistTwo, $value);
}
}
//Printing Final third list [6, 12, 18, 4, 12, 20, 28]
print_r(array_merge($NlistOne,$NlistTwo));
?>
Output will be:
Array ( [0] => 6 [1] => 12 [2] => 18 [3] => 4 [4] => 12 [5] => 20 [6] => 28 )
//init result array
//loop over listOne, using for($i=1;$i<sizeof($listOne);$i=$i+2)
//and add to result for each iteration, $resultArr[] = $listOne[$i]
//do the same with listTwo, but for($i=*0*
You can merge both of arrays and then pick all odd elements
$listOne = [3, 6, 9, 12, 15, 18, 21];
$listTwo = [4, 8, 12, 16, 20, 24, 28];
$result = [];
foreach ( array_merge($listOne, $listTwo) as $value ){
if ( $key % 2 ) {
$result[] = $value;
}
}
If array length isn't fixed, say it could contain not 7 elements, then you need to check it before merging to make it have odd number of elements
$listOne = [3, 6, 9, 12, 15, 18, 21, 777];
$listTwo = [4, 8, 12, 16, 20, 24, 28];
$result = [];
if ( count($listOne) % 2 !== 1 ) {
$listOne[] = 0;
}
foreach( array_merge($listOne, $listTwo) as $value ){
if ( $key % 2 ) {
$result[] = $value;
}
}
you don't have to loop over whole array array_filter will do this for you, Constant ARRAY_FILTER_USE_KEY will check each key for odd or for even
<?php
$a1 = [3, 6, 9, 12, 15, 18, 21];
$a2 = [4, 8, 12, 16, 20, 24, 28];
function odd($var)
{
// returns whether the input integer is odd
return $var & 1;
}
function even($var)
{
// returns whether the input integer is even
return !($var & 1);
}
$result= (array_merge(array_filter($a1, 'odd', ARRAY_FILTER_USE_KEY),array_filter($a2, 'even', ARRAY_FILTER_USE_KEY)));
output you will get
Array (
[0] => 6
[1] => 12
[2] => 18
[3] => 4
[4] => 12
[5] => 20
[6] => 28 )
Iterate over first one and take only values of odds indices, and loop again through second one and take evens indices.
$listOne = [3, 6, 9, 12, 15, 18, 21];
$listTwo = [4, 8, 12, 16, 20, 24, 28];
$res = [];
for ($i=0; $i < count($listOne); $i++) {
if($i & 1) // $i is odd.
$res[] = $listOne[$i];
}
for ($j=0; $j < count($listTwo); $j++) {
if(n % 2 === 0) // $j is even.
$res[] = $listTwo[$j];
}
Result:
echo "List One :".json_encode($listOne)."<br>";
echo "List Two :".json_encode($listTwo)."<br>";
echo "Lists Merged:".json_encode($res);
Output:*
/*
List One :[3,6,9,12,15,18,21]
List Two :[4,8,12,16,20,24,28]
Lists Merged:[6,12,18,4,12,20,28]
*/
Iterate over arrays:
take odds in array starting with index One and increment it by two.
take evens in array by starting with index Zero and increment it by two.
$listOne = [3, 6, 9, 12, 15, 18, 21]; $listTwo = [4, 8, 12, 16, 20, 24, 28];
$res = [];
for ($i=1; $i < count($listOne); $i+=2) {
$res[] = $listOne[$i];
}
for ($j=0; $j < count($listTwo); $j+=2) {
$res[] = $listTwo[$j];
}
print(json_encode($res)); // [6,12,18,4,12,20,28]

Finding higher and lower numbers in an array and storing in one array

I need to get the closest lowest and highest to a number.
Attempt
<?php
$a = array(1, 8, 23,42,47, 52, 55, 66, 74,75, 76,77,78, 95,);
sort($a);
$v = 58;
$lesser = null;
$greater = null;
foreach($a as $key => $current){
if($current <= $v){
$lesser = $current;
$greater = $a[($key+1)];
}else{
}
}
print_r(array(
"lesser" => $lesser,
"greater" => $greater,
));
?>
/** output :
Array
(
lesser => 55
greater => 66
)
**/
My aim is to get all the numbers greater to the given number, and the same with the lesser:
greater => 66, 74, 75, 77, 78, 95
lesser => 55, 52, 47, 42, 23, 8, 1
How do I solve this problem?
Make $lesser and $greater arrays that you push onto, instead of replacing.
<?php
$a = array(1, 8, 23,42,47, 52, 55, 66, 74,75, 76,77,78, 95,);
$v = 58;
$lesser = [];
$greater = [];
foreach($a as $key => $current){
if ($current < $v) {
$lesser[] = $current;
} elseif ($current > $v) {
$greater[] = $current;
}
}
print_r(array(
"lesser" => $lesser,
"greater" => $greater,
));
?>

Find how many numbers are greater than N in an array

If I have an indexed PHP array:
$array = array(2, 12, 23, 34, 36, 36, 36, 56);
And I have a variable:
$number = 30;
How do I calculate the number of "array positions" that are higher than $number?
For example, the function should return 5, because there are 5 numbers (34, 36, 36, 36 and 56) that are higher than 30.
Edit: I've already tried different methods of counting the array values, but I have no idea how to count the positions. It has me stumped.
Can also use
array_reduce — Iteratively reduce the array to a single value using a callback function
Example:
$array = array(2, 12, 23, 34, 36, 36, 36, 56);
$number = 30;
echo array_reduce($array, function($ret, $val) use ($number) {
return $ret += $val > $number;
});
Or hardcode the number into the callback
echo array_reduce($array, function($ret, $val) {
return $ret += $val > 30;
});
As another alternative, use array_filter() to remove the elements from the array that you don't want, then just count() the remaining list...
$array = array(2, 12, 23, 34, 36, 36, 36, 56);
$number = 30;
$gtn = array_filter($array, function($value) use ($number) { return $value > $number; });
echo count($gtn);
$gtn will contain the numbers (34, 36, 36, 36, 56), which may be useful for other things in your code.
You don't need to iterate the full array.
If you first sort the array then as soon as you find a larger number you can break the loop and use the key value from there.
$array = array(2, 12, 23, 34, 36, 36, 36, 56);
Sort($array);
$number = 30;
Foreach($array as $key => $val) If($val >= $number) break;
$larger = array_slice($array, $key);
Echo count($larger) . "\n";
Var_dump($larger);
Output:
5 //echo
array(5) { // var_dump
[0] => 34
[1] => 36
[2] => 36
[3] => 36
[4] => 56
}
https://3v4l.org/8FoOP
You can use array_reduce for this task:
$array = array(2, 12, 23, 34, 36, 36, 36, 56);
$number = 30;
$cnt = array_reduce($array, function ($carry, $item) use ($number) {
if ( $item > $number ) {
$carry++;
}
return $carry;
});
echo $cnt;
Try this code:
function findGreaterNumberCount($array, $number) {
$count = 0;
foreach ($array as $value) {
if ($value > $number) {
$count++;
}
}
return $count;
}
echo findGreaterNumberCount(array(2, 12, 23, 34, 36, 36, 36, 56), 30);
This platform doesn't recommend to write code. So you should try something before asking a question. Be careful next time.
use array reduce and make your code short
$array = [2, 12, 23, 34, 36, 36, 36, 56];
$number = 30;
$totalNumberOfItems = array_reduce($array, function ($sum, $item) use ($number) {
if($item > $number)
$sum++;
return $sum;
});
Var_dump($cnt);
You can iterate array with array_filter to find the greatest array element.
$num = 30;
$array = array(2, 12, 23, 34, 36, 36, 36, 56);
$a = array_filter($array, function($value) use( $num ){
return $num < $value;
});
print_r($a);
Out put
Array
(
[3] => 34
[4] => 36
[5] => 36
[6] => 36
[7] => 56
)

Counting, highlighting and printing the duplicates between two arrays

First time posting on stackoverflow.
After printing the main array, I have managed to highlight the values that are found in the second one, but I also want to print the number of times that the duplicate occurs in brackets at the same time. I have run out of the ideas on how to do that last part, I get stuck in multiple loops and other problems. I will paste here what's working for now.
The code:
$main = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20 );
$secondary = array( 1, 6, 10, 6, 17, 6, 17, 20 );
foreach ( $main as $number )
{
if ( in_array( $number, $secondary ) )
{
echo $item;
// this one is supposed to be highlighted, but the html code disappears on stackoverflow
/* this is where the number of duplicates should appear in bracket, example:
highlighted number( number of duplicates ) */
}
else
{
echo $item;
// this one is simple
}
}
EXPECTED RESULT:
1(1), 2, 3, 4, 5, 6(3), 7, 8, 9, 10(1), 11, 12, 13, 14, 15, 16, 17(2), 18, 19, 20(1)
Basically the brackets contain the number of times that the value is found in the second array, aside from being colored, but I can't paste the html code for some reason. Sorry for not making the expected result more clear !
PROBLEM SOLVED:
Thanks to everyone for your help, first time using this website, didn't expect such a quick response from you guys. Thank you very much !
You need to get the count values of your secondary array first using array_count_values. This is what you can acquire as
$main = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
$secondary = array(1, 6, 10, 6, 17, 6, 17, 20);
$count_values = array_count_values($secondary);
foreach ($main as $key => $value) {
if (in_array($value, $secondary)) {
echo $value . "<strong>(" . $count_values[$value] . ")</strong>";
echo ( ++$key == count($main)) ? '' : ',';
} else {
echo $value;
echo ( ++$key == count($main)) ? '' : ',';
}
}
Output:
1(1),2,3,4,5,6(3),7,8,9,10(1),11,12,13,14,15,16,17(2),18,19,20(1)
Assuming $secondary is the one with the dupes, you should go about it the other way:
$dupes = array();
foreach($secondary as $number) {
if (in_array($number, $main)) {
$dupes[$number]++;
}
}
var_dump($dupes);
<?php
$main = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12, 13, 14, 15, 16, 17,18,19,20);
$secondary = array( 1, 6, 10, 6, 17, 6, 17, 20 );
$result =array();
foreach($main as $key => $value){
$i=0;
foreach($secondary as $key1 => $value1){
if($value == $value1){
$i++;
}
$result[$value] = $i;
}
}
$resultString ='';
foreach($result as $key => $value){
$resultString .=$key.'('.$value.'),' ;
}
echo trim($resultString,',');
?>
Result:
1(1),2(0),3(0),4(0),5(0),6(3),7(0),8(0),9(0),10(1),11(0),12(0),13(0),14(0),15(0),16(0),17(2),18(0),19(0),20(1)

see if 3 or more numbers match an array

Hay i have an array consisting for 6 random numbers, here's an example
[4,8,12,22,23,43]
I also have 100 arrays containing 6 numbers, these are all random a few examples could be
[5,8,15,47,32,48]
[3,4,8,12,33,42]
[8,12,26,55,43,33]
[4,63,45,23,45,55] ...
I want to see how many times (out of the array of 100) these numbers match at least 3 from the top array. As you can guess this is a lottery experiment.
As you can see array number 3 matches 3 numbers from the top array.
Any ideas how do do this? With perhaps an option to see if 4 numbers matched.
$master_array = array(4, 8, 12, 22, 23, 43);
$arrays = array(array(5, 8, 15, 47, 32, 48),
array(3, 4, 8, 12, 33, 42),
array(8, 12, 26, 55, 43, 33),
array(4, 63, 45, 23, 45, 55));
foreach ($arrays as $arr)
{
$intersect = array_intersect($master_array, $arr);
if (count($intersect)==3) print 'Match: '.print_r($arr, true).PHP_EOL;
}
maybe smth like this:
$winner = [4,8,12,22,23,43];
$arrays = //all your 100 arrays
$i = 0; // number of matches
foreach ($arrays as $array)
{
$result = array_intersect($array, $winner);
if (count($result) >= 3) $i++;
}

Categories