Counting, highlighting and printing the duplicates between two arrays - php

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)

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]

Show top 3 random posts on Wordpress

I have custom page where there are 10 posts showing right now, what i need to show first 3 random then next 4-7 again random and 8-10 again random
Is their any way i can manage in the while loop
<?php
$count = 1;
while ( $loop->have_posts() ) : $loop->the_post();
echo the_title();
$count++;
endwhile;
?>
Thanks
If I understood you correctly, this should get you close to what you want.
Put your posts into an array first:
$posts = array();
while ( $loop->have_posts() ) {
$loop->the_post();
array_push($posts, $post);
}
Then sort that array. I'll demonstrate with 0-9:
$array = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
$first = array_slice($array, 0, 3);
$second = array_slice($array, 3, 4);
$third = array_slice($array, 7, 3);
shuffle($first);
shuffle($second);
shuffle($third);
$newarray = array_merge($first, $second, $third);
print join(", ", $array) . "\n" . join(", ", $newarray) . "\n";
Which will lead to a random-ish sorting of the array while keeping "blocks" (top, middle, bottom) in the same order:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
1, 2, 0, 6, 5, 4, 3, 8, 7, 9
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
0, 2, 1, 3, 4, 5, 6, 9, 8, 7
Putting it all together:
$posts = array();
while ( $loop->have_posts() ) {
$loop->the_post();
array_push($posts, $post);
}
$first = array_slice($posts, 0, 3);
$second = array_slice($posts, 3, 4);
$third = array_slice($posts, 7, 3);
shuffle($first);
shuffle($second);
shuffle($third);
$newposts = array_merge($first, $second, $third);
foreach($newposts as $mypost) {
print $mypost->post_title . "<br />\n";
}
note that I erroneously had written push $posts, $post; instead of array_push($posts, $post);, I have written a lot of Perl lately, and it shows.

For-each loop, larger than 20 into another array

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, )

Find peaks in a series?

I have got a series like this:
14, 13, 12, 14, 15, 18, 20, 17, 15, 19, 22, 24, 22, 18, 15, 14, 17, ...
If I plot these points on a chart on X-Y axis using these values as Y coordinates, then you'll see that there are peaks at 20 & 24.
I want to find all these peaks in the series
I tried:
$a=array(14, 13, 12, 14, 15, 18, 20, 17, 15, 19, 22, 24, 22, 18, 15, 14, 17 );
rsort($a);
echo $a[0];
echo $a[1];
But that doesn't give me the two peaks I see on the graph. The result of the code above is 24, and 22. But the peak on the graph were made by 20 and 24...
Is there a way I can detect the array to determine the peaks in the entire series?
I don't need a working code. Just some ideas I can work upon.
As Mark Baker suggested, you need to check that each value in the array is greater than the previous and the next value. That's what defines a peak.
Just be sure to start from the 2nd index and finish on the nth-1 item or else you'll get an Undefined offset error.
$a = array(14, 13, 12, 14, 15, 18, 20, 17, 15, 19, 22, 24, 22, 18, 15, 14, 17);
$arr = [];
for($i=1; $i<count($a)-1; $i++){
if($a[$i] > $a[$i+1] && $a[$i] > $a[$i-1]) {
array_push($arr, $a[$i]);
}
}
var_dump($arr); //returns: array(2) { [0]=> int(20) [1]=> int(24) }
Depending on your application, you might want to add some logic in case the case that 2 or more items "together" are a peak. For example, 22, 24, 24, 22, 18. If this is something you want, just change the logic to check for >= on the next item:
if($a[$i] > $a[$i+1] && $a[$i] >= $a[$i-1]) {
This will yield the same result as above.
<?php
$a=array(14, 13, 12, 14, 15, 18, 20, 17, 15, 19, 22, 24, 22, 18, 15, 14, 17 );
$last=0;
$peaks=array();
$upwards=false;
foreach( $a as $value )
{
if( $value > $last )
{
$upwards = true;
}
if( $value < $last )
{
if( $upwards )
{
$peaks[] = $last;
}
$upwards = false;
}
$last = $value;
}
var_dump($peaks);
Old question, guess it popped up because someone was editing, but here's my two cents' worth. This is better done without a loop:
<?php
$a = [14, 13, 12, 14, 15, 18, 20, 17, 15, 19, 22, 24, 22, 18, 15, 14, 17];
$b = array_filter(
$a,
function($v, $k) use($a) {return $k > 0 && $v > $a[$k-1] && $k + 1 < count($a) && $v > $a[$k+1];},
ARRAY_FILTER_USE_BOTH
);
print_r($b);
Result:
Array
(
[6] => 20
[11] => 24
)

PHP reorder an array at random

I need to reorder an array at random but I am not sure what the best/cleanest/fastest way is to do this.
So what I am trying to achieve is the following. Let's say I have an array that looks like this:
$array = array(4, 4, 4, 4, 6, 6, 6, 6, 8, 8, 10, 10, 20, 40, 60);
My goal is to get something like this but at random:
$array = array(6, 4, 4, 10, 4, 6, 4, 6, 60, 6, 8, 6, 10, 40, 8, 20);
Here's what I've been trying but it doesn't seem to be working as intended:
$array = array(4, 4, 4, 4, 6, 6, 6, 6, 8, 8, 10, 10, 20, 40, 60);
$newArray = array();
$randomNumber = rand(0 , 14);
for ($x = 0; $x <= 15; $x++) {
$newArray[$x] = $array[$randomNumber];
}
Many thanks in advance to anyone who can help me out :)
Use shuffle() function.
shuffle($array);
http://php.net/manual/en/function.shuffle.php
$array = array(4, 4, 4, 4, 6, 6, 6, 6, 8, 8, 10, 10, 20, 40, 60);
Check the output of previous array
echo "<pre>";
print_r($array);
echo "</pre>";
Shuffling previous array & check output again.
shuffle($array);
print_r($array);
Now run a foreach loop like
foreach($array as $item){
echo $item;
}
Note: You don't need to store shuffle data to new array.

Categories