Loop through an array (+100 values) [duplicate] - php

This question already has answers here:
Show the two elements in foreach loop in every iteration? [duplicate]
(4 answers)
Closed 1 year ago.
This is my array:
$my_array = array("1", "2", "3", "4");
I want to achieve something like this:
1 vs 2
3 vs 4
Because the length of my array is only 4 it was easy for me to do this:
echo $my_array[0]." vs ".$my_array[1];
echo "<br>";
echo $my_array[2]." vs ".$my_array[3];
But how can I achieve this if my array has more than 100 values? I also want to account for odd numbers of array elements.

You can use a "for" loop, with an increment of two for every loop :
$len = count($my_array);
for($i=0; $i<$len; $i=$i+2) {
echo $my_array[$i]." vs ".$my_array[$i+1]."<br/>;
}
If you're not sure your array always contains an even number of indexes, you can add a condition in order to ignore the last case if there is no more pair to do.
$len = count($my_array);
for($i=0; $i<$len; $i=$i+2) {
if($i !== $len-1) {
echo $my_array[$i]." vs ".$my_array[$i+1]."<br/>;
}
}

Sure, for loop is the obvious answer, but there are more interesting ones ;)
$my_array = ["1", "2", "3", "4"];
$new_array = array_map(
function($v) {return isset($v[1]) ? "$v[0] vs $v[1]<br/>" : null; },
array_chunk($my_array, 2)
);
print_r($new_array);
Output:
Array
(
[0] => 1 vs 2<br/>
[1] => 3 vs 4<br/>
)

You can use a for loop to loop through the array.
$my_array = array("1", "2", "3", "4","5","6");
for ($x = 0; $x < sizeof($my_array); $x = $x+2) {
echo $my_array[0+$x]." vs ".$my_array[1+$x];
echo "<br>";
}

Related

Why does For work, but ForEach does not in PHP? [duplicate]

This question already has answers here:
Why can't I update data in an array with foreach loop? [duplicate]
(3 answers)
Closed 1 year ago.
We have an array of strings of numbers
$a = ["1", "2", "3"];
foreach loop doesn't change the type, result: [0]=>string(1) "1"
foreach ($a as $v) $v = (int) $v;
for loop makes ints from strings, result: [0]=>int(1)
for ($i = 0; $i < count($a); $i++) $a[$i] = (int) $a[$i];
Please, explain why is that?
The same reason that
$v = $a[0];
$v = int($v);
doesn't change $a. $v is a copy of the array element, not a reference to it.
You can make it work using a reference variable
foreach ($a as &$v) {
$v = (int)$v;
}

Use variables in the name of the variable [duplicate]

This question already has answers here:
variable variables
(5 answers)
Closed 3 years ago.
I have two arrays:
$my_array1= array("A", "B");
$my_array2= array("1", "2");
Is it possible to use variables ($x) in the index of the array like this:
for ($x = 1; $x <= 2; $x++) {
Echo $my_array.$x[0];
}
How to achieve this?
After referred in comment , i think it's work : here
$my_array1= array("A", "B");
$my_array2= array("1", "2");
and re-use your loop like:
for ($x = 1; $x <= 2; $x++) {
// to init the new name of array
$init = 'my_array'.$x;
// to use variable in the name of variable
Echo $$init[0];
}
I hope it's help you
I think what you're looking for is to be able to use key / value pairs.
You can do something like:
$array = array(
1 => "a",
2 => "b",
3 => "c",
4 => "d",
);
foreach ($array as $key => $value) {
echo "{$key} => {$value} ";
}
Or loop througout the numeric key values as you like.

Sorting of some strings?

I can only imagine that this is fairly simple, and yet the solution eludes me.
Let assume I have the following variables:
$group1 = "5";
$group2 = "1";
$group3 = "15";
$group4 = "3";
$group5 = "7";
$group6 = "1";
$group7 = "55";
$group8 = "0";
$group9 = "35";
I want the groups listed with the highest amount first e.g.:
Group 7 is number 1 with 55.
Group 9 is number 2 with 35.
Group 3 is number 3 with 15.
Group 5 is number 4 with 7.
Group 1 is number 5 with 5.
Group 4 is number 6 with 3.
Group 2 is number 7 with 1.
Group 6 is number 8 with 1.
Group 8 is number 9 with 0.
Perhaps it would be easier to list all the data in a double-array and then sort it?
First of all, use arrays(just usual arays).
If you array is
$group = array(1 => 5, 2 => 1 ... )
You may use arsort function.
Here I use numbers, not strings. If you will use strings (for values) you need a flag for sort (SORT_NUMERIC)
More information in PHP Manual
Then use foreach
foreach($group as $key => $value){
$key is number of varaiable
$value is value of it.
you also may add counter to print 1,2,3...
}
use arrays for this purpose
$group[1] = "5";
$group[2] = "1";
$group[3] = "15";
$group[4] = "3";
$group[5] = "7";
$group[6] = "1";
$group[7] = "55";
$group[8] = "0";
$group[9] = "35";
and then sort it.
arsort($group, SORT_NUMERIC); // SORT_NUMERIC suggested by **fab**
Just have your data inside an associative array, and sort it with an association aware sort:
$groups = array(
'group1' => "5",
'group2' => "1",
'group3' => "15",
'group4' => "3",
'group5' => "7",
'group6' => "1",
'group7' => "55",
'group8' => "0",
'group9' => "35",
);
arsort($groups);
// iteration as usual
foreach ($groups as $group_name => $value) {
}
// getting elements with the array functions based around the array's internal pointer
reset($groups); // reset the pointer to the start
print key($groups); // the first element's key
print current($groups); // the first element's value
next($groups); // moving the array to the next element
Yes using an array is the best thing to do.
something like that
$group[1]="5";
$group[2]="1";
After that you can sort your array
The best way to do this is with an array and arsort. This will keep your indexes intact.
arsort returns a boolean so do not assign to a new variable
$groups = array("5","1","15","3","7","1","55","0","35");
arsort($groups, SORT_NUMERIC);
$i = 1;
foreach ($groups as $key => $val) {
echo 'Group ' . $key . ' is number ' . $i . ' with ' . $val;
$i++;
}
Put your groups in an array
$groups = array("5","1","15","3","7","1","55","0","35");
arsort($groups); //This sort the array is descending order
var_dump($sorted_groups);
To print the array in your format use the following function
count = 1;
foreach($groups as $key => $value) {
echo "Group ".($key+1)." is number ".$count++." with ".$value;
}

Calculate the highest duplicate integers of two associative arrays

Given 2 associative arrays:
$fruits = array ( "d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple" );
$fruits2 = array ( "e" => "lemon", "f" => "apple", "g" => "melon", "h" => "apple" );
I would like to do something like:
for ( $n = count($fruits), $i = 0; $i < $n; $i++)
{
$test = (bool) $fruits[$i] == $fruits2[$i];
}
This can not work as I am using associative array. What would be the best way to go to achieve that? (This loops is going to be ran intensity so I would like to keep it as light as possible)
EDIT to give more detail on what I am trying to do:
Here is a better example of what I am trying to achieve:
$array = array ( 1,2,3,4,3,2 );
$array2 = array ( 9,6,3,4,3,2 );
$counts = array_count_values( $words );
$counts2 = array_count_values( $words2 );
Given the arrays above I need to calculate which array as the highest duplicate integers. Imagine a poker game, comparing two hands that each contain duplicate cards, how to evaluate which set of duplicate (whether double, triple or quadruple ) as the highest value.
Use array array_values ( array $input ) function and compare them.
$value1=array_values($fruits);
$value2=array_values($fruits2);
for ( $i = 0; $i < count($value1); $i++)
{
$test[] = $value1[$i] == $value2[$i] ? TRUE : FLASE;
}
Got it working this way :
$n = count($fruits);
for ( $i = 0; $i < $n; $i++)
{
$cur_vals_1 = each ($fruits);
$cur_vals_2 = each ($fruits2);
$sum1 += $cur_vals_1['key'] * $cur_vals_1['value'];
...
}
You're probably chasing the wrong solution. To find the highest duplicate in an array I'd use this (PHP 5.3+ syntax):
max(array_keys(array_filter(array_count_values($array), function ($i) { return $i >= 2; })))
Do this for both arrays and compare which result is higher. Trying to compare both against each other at the same time is too convoluted.
You don't need the ternary operator.
Also, be careful with count() as it will fail if your array is null.
They also need to be equal lengths or you'll get an error.
if( is_array($value1) && is_array($value2) && count($value1)==count($value2) ) {
for ( $i = 0; $i < count($value1); $i++)
{
$test[] = ($value1[$i] == $value2[$i]);
}
}

Find min/max values in a multidimensional array

I need to find the minimum and maximum in a multidimensional array in PHP, I have what I thought would work below but it keeps giving me a parse error, this is homework and I am not asking anyone to do it for me but I am a beginner and any help would be appreciated.
<?php
/* 2 dimensional array in PHP - strictly an array of arrays */
$multable[] = array("11", "12", "15", "22", "41", "42");
$multable[] = array("6", "7", "16", "17", "22", "23");
$multable[] = array("1", "15", "16", "20", "22", "3");
<table>
<?php
/* display a table from a 2D array */
for ($j=0;$j<3;$j++) {
print "<tr>";
for ($k=0;$k<6;$k++) {
echo "<td>",$multable[$j][$k],"</td>";
}
print "</tr>";
$max_value = 0;
foreach ($multable as $myMax) {
if ($max_value<$myMax) {
$max_value = $myMax;
}
}
echo $max_value;
?>
</table>
There is also a one-liner for that:
$max = max( array_map("max", $multable) );
use max() and min() functions of php.
Max:
<?php
$multable = array();
$multable[] = array("11", "12", "15", "22", "41", "42");
$multable[] = array("6", "7", "16", "17", "22", "23");
$multable[] = array("1", "15", "16", "20", "22", "3");
$max = -99999999;
foreach($multable as $sub){
$tempMax = max($sub);
if($tempMax > $max){
$max = $tempMax;
}
}
echo $max;
?>
You can figure out min :)
Your foreach iteration only does one dimension - each $myMax is one of your six element lists and not an individual scalar value. That's why your comparison doesn't work and the conditional is never true, you are trying to compare a scalar with an array. What you call $myMax would more appropriately be called $currentRow
This is ok because PHP has some functions to find the min and max of an array
http://us.php.net/manual/en/function.min.php
http://us.php.net/manual/en/function.max.php
$max_value = 0; $min_value = $multable[0][0];
foreach ($multable as $currentRow)
{
// COMPARE CURRENT ROW's MIN/MAX TO MIN/MAX_VALUE
// AND MAKE NEW ASSIGNMENT IF APPROPRIATE
}
Or hand this in and see what your teacher says:
function fComp ($f) {return function ($a,$b) use ($f) {return $f($a, $f($b));};}
$max = array_reduce($multable, fComp('max'), $multable[0][0]);
$min = array_reduce($multable, fComp('min'), $multable[0][0]);
echo "max: $max <br />";
echo "min: $min";
PS - in your earlier iterations to make the HTML table, it would be good form to lose the constants. Use count to get the length of the array instead - or better yet - use foreach like you do later on. (Even with foreach you would still need two of them nested, it doesn't iterate a 2-dimensional array element-by-element)
For Minimum value
echo min(array_map("min", $multable));
For Maximum Value
echo max(array_map("max", $multable));
$minArray = array();
foreach($arrayVal as $arrI=> $arrK)
{
if($arrK == min($arrayVal ) )
{
array_push($minArray , $arrayVal );
}
}
print_r($minArray);
Here you go :)
I do not recommend calling min() or max() on each subarray, then calling the function again on the reduced array. This is making too many calls and won't be most efficient.
Instead, flatten the indexed array just once with a spread&merge technique, then call min() or max() just once on the flattened array.
Code: (Demo)
$flat = array_merge(...$multable);
printf(
'Min: %d, Max: %d',
min($flat),
max($flat)
);
Output:
Min: 1, Max: 42
If you only need one or the other outcome, then don't bother with the temporary variable.
echo min(array_merge(...$multable));
Or
echo max(array_merge(...$multable));

Categories