PHP Array.length for a two dimensional array (y axis) - php

I am trying to use a function whereby I see how tall (y axis) a two dimensional array is in PHP. How would you suggest that I do this? Sorry, I am new to PHP.

max(array_map('count', $array2d))

If the y-axis is the outer array, then really just count($array). The second dimension would just be count($array[0]) if it's uniform.

A multi-dimensional array is simply an array of arrays -- it's not like you've blocked out a rectangular set of addresses; more like a train where each car can be stacked as high as you like.
As such, the "height" of the array, presumably, is the count of the currently largest array member. #phihag has given a great way to get that (max(array_map(count, $array2d))) but I just want to be sure you understand what it means. The max height of the various arrays within the parent array has no effect on the size or capacity of any given array member.

$max = 0;
foreach($array as $val){
$max = (count($val)>$max?count($val):$max)
}
where $max is the count you are looking for

In my application I have used this approach.
$array = array();
$array[0][0] = "one";
$array[0][1] = "two";
$array[1][0] = "three";
$array[1][1] = "four";
for ($i=0; isset($array[$i][1]); $i++) {
echo $array[$i][1];
}
output: twofour
Probably, this is not the best approach for your application, but for mine it worked perfectly.

To sum up the second dimension, use count in a loop:
$counter = 0;
foreach($var AS $value) {
$counter += count($value);
}
echo $counter;

1.dimension:
count($arr);
2.dimension:
function count2($arr) {
$dim = 0;
foreach ($arr as $v) {
if (count($v) > $dim)
$dim = count($v);
}
return $dim;
}
As it is possible to have each array / vector of different length (unlike a mathematical matrix) you have to look for the max. length.

Related

Consolidate array of numbers without exceeding a predefined maximum value per element

I'm trying to combine numbers in an array by adding them so that the max value can only by 30.
For example, this is my array:
array(10,30,10,10,15);
After combining the numbers in the array to items with a max value 30, the result should be:
array(30,30,15);
How to achieve this?
I'm trying to combine numbers in an array by adding them so that the
max value can only by 30
So, when you combine numbers, you can achieve the lowest possible set of values in your array and also make sure that max value remains 30 by:
First, sort them.
Second, keeping adding elements to sum till you are about to get a sum > 30.
Third, once an element can no longer be added to a sum, add the current sum in your array and make the current element as the new sum.
Code:
<?php
$arr = array(10,30,10,10,15);
sort($arr);
$res = [];
$curr_sum = 0;
foreach($arr as $each_value){
if($curr_sum + $each_value <= 30) $curr_sum += $each_value;
else{
$res[] = $curr_sum;
$curr_sum = $each_value;
}
}
$res[] = $curr_sum;
print_r($res);
Demo: https://3v4l.org/BYhuE
Update: If order of the numbers matters, seeing your current output, you could just use rsort() to show them in descending order.
rsort($res);
$total = array_sum(array(10,30,10,10,15)); //assign sum totals from orignal array
$maxValue = 30; //assign max value allowed in array
$numberOfWholeOccurancesOfMaxValue = floor($total/$maxValue);
$remainder = $total%$maxValue;
//build array
$i=0;
while ( $i < $numberOfWholeOccurancesOfMaxValue ){
$array[] = $maxValue;
$i++;
}
$array[] = $remainder;
print_r($array);
You can loop only once to get this,
$temp = array(10,30,10,10,15);
natsort($temp); // sorting to reduce hustle and complication
$result = [];
$i = 0;
$maxValue = 30;
foreach($temp as $v){
// checking sum is greater or value is greater or $v is greater than equal to
if(!empty($result[$i]) && (($result[$i]+$v) > $maxValue)){
$i++;
}
$result[$i] = (!empty($result[$i]) ? ($result[$i]+$v) : $v);
}
print_r($result);
Working demo.
I believe finding most space-optimized/compact result requires a nested loop. My advice resembles the firstFitDecreasing() function in this answer of mine except in this case the nested loops are accessing the same array. I've added a couple of simple conditions to prevent needless iterations.
rsort($array);
foreach ($array as $k1 => &$v1) {
if ($v1 >= $limit) {
continue;
}
foreach ($array as $k2 => $v2) {
if ($k1 !== $k2 && $v1 + $v2 <= $limit) {
$v1 += $v2;
unset($array[$k2]);
if ($v1 === $limit) {
continue 2;
}
}
}
}
rsort($array);
var_export($array);
By putting larger numbers before smaller numbers before processing AND by attempting to add multiple subsequent values to earlier values, having fewer total elements in the result is possible.
See my comparative demonstration.
I believe #Clint's answer is misinterpreting the task and is damaging the data by summing all values then distributing the max amounts in the result array.
With more challenging input data like $array = [10,30,5,10,5,13,14,15,10,5]; and $limit = 30;, my solution provides a more dense result versus #nice_dev's and #rahul's answers.

create array using loop and input arithmetic progression value using loop

I'm noob in PHP programming and for my surprise I found it difficult to create an array using loop and to input in it values using arithmetic progression with +4 difference.I spent over an hour and tried a lot of code,searched so many examples.Below is my code that work(maybe) but not properly.
<?php
$array = [];
for($x=0;$x<10;$x++){
for($i=0;$i<100;$i+=4){
$array[] = $i;
}
break;
}
var_dump($array);
?>
I must have no more than 10(0-9 key) values,but because of $i the loop continues to 96 up to 24 keys.Maybe it's stupid question but I've totally blocked.
Is that what you want ?
<?php
$array = [];
for($x=0;$x<10;$x++){
$array[] = $x*4;
}
var_dump($array);
?>
Or maybe simpler
$array = range(0,36,4);
Doc for range : http://php.net/manual/fr/function.range.php
Then perhaps you have been overthinking this. You just need one loop, and can simply scale your key by 4:
foreach (range(0, 10) as $x) {
$array[] = 4 * $x;
}
Which will just add 0 for key 0, and 4 for key 1, and so on.
Note that for larger ranges, you should keep the classic for of course. It's more readable/obvious for math thingys anyway.
Use this:-
for ($x = 0; $x < 10; $x++) {
$array[$x] = $x * 4;
}
echo '<pre>';
print_r($array);
I think you must read basic of array here is a link that is useful for you link

Using an index twice in PHP

I am trying to use a for loop where it looks through an array and tries to make sure the same element is not used twice. For example, if $r or the random variable is assigned the number "3", my final array list will find the value associated with wordList[3] and add it. When the loop runs again, I don't want $r to use 3 again. Example output: 122234, where I would want something along the lines of 132456. Thanks in advance for the help.
for($i = 0; $i < $numWords; $i++){
$r = rand(0, $numWords);
$arrayTrack[$i] == $r;
$wordList[$r] = $finalArray[$i];
for($j = 0; $j <= $i; $j++){
if($arrayTrack[$j] == $r){
# Not sure what to do here. If $r is 9 once, I do not want it to be 9 again.
# I wrote this so that $r will never repeat itself
break;
}
}
Edited for clarity.
Pretty sure you are over complicating things. Try this, using array_rand():
$final_array = array();
$rand_keys = array_rand($wordList, $numWords);
foreach ($rand_keys as $key) {
$final_array[] = $wordList[$key];
}
If $numWords is 9, this will give you 9 random, unique elements from $wordList.
See demo
$range = range(0, $numWords - 1); // may be without -1, it depends..
shuffle($range);
for($i = 0; $i < $numWords; $i++) {
$r = array_pop($range);
$wordList[$r] = $finalArray[$i];
}
I do not know why you want it.. may be it is easier to shuffle($finalArray);??
So ideally "abcdefghi" in some random order.
$letters = str_split('abcdefghi');
shuffle($letters);
var_dump($letters);
ps: if you have hardcoded array $wordList and you want to take first $n elements of it and shuffle then (if this is not an associative array and you do not care about the keys)
$newArray = array_slice($wordList, 0, $n);
shuffle($newArray);
var_dump($newArray);
You can try array_rand and unset
For example:
$array = array('one','two','free','four','five');
$count = count($array);
for($i=0;$i<$count;$i++)
{
$b = array_rand($array);
echo $array[$b].'<br />';
unset($array[$b]);
}
after you have brought the data in the array, you purify and simultaneously removing the memory array
Ok... I have NO idea why you are trying to use so many variables with this.
I certainly, have no clue what you were using $arrayTrack for.
There is a very good chance I am mis-understanding all of this though.
<?php
$numWords=10;
$wordList=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$finalArray=array();
for ($i=0; $i<$numWords; $i++) {
start:
$r=rand(0,$numWords);
$wordChoice=$wordList[$r];
foreach ($finalArray as $word) {
if ($word==$wordChoice) goto start;
}
$finalArray[]=$wordChoice;
}
echo "Result: ".implode(',',$finalArray)."\n";

Compare single value against array - substitute the value for closest number within array

Title is lengthy and confusing, forgive me.
$array = (1,5,10,25,50);
$x = 8
How would I compare $x to each value within the array, and then select the value with the closest match.
In this case, it would be 10.
I imagined creating a handful of if statements but thought there could be a better way to do this.
Thanks in advance
Another way, using an intermediate array with the differences:
$diff = array();
foreach($array as $n)
$diff[$n] = abs($x - $n); // key = number, value = difference
// get the key that contains the smallest difference
$closest = array_search(min($diff), $diff);
$min = 0;
foreach ($array AS $i => $v) {
if (abs($array[$min] - $x) > abs($v - $x))
$min = $i;
// you can optimize this with :
if ($v == $x)
break;
}
$closest = $array[$min];
Something like that should work.

How to do PHP matrix operation easily and gracefully?

I've a $max which is essentially a two dimensional array.
Each element in $max is eithor 1 or 0,
can be denoted by $max[$x][$y], where $x is an integer within 0~WIDTH,similar for $y
My purpose is to find rows and columns in the $maxthat sums up greater than a CONSTANT, and get the average distance between rows/columns that qualify.
Anyone has a good solution ?
I have not tested this, but it should work for summing up the columns and rows:
//Map columns and rows into their respective values
//Note that we preserve the col/row indexes
$rowval = array();
$colval = array();
foreach($max as $k1 => $row) {
$rowval[$k1] = array_sum($row);
foreach($row as $k2 => $col) {
if(!isset($colval[$k2])) {
$colval[$k2] = 0;
}
$colval[$k2] += $col;
}
}
//Define filter function
function is_over($val) {
return $val > CONSTANT;
}
//Filter out the cols/rows from their respective arrays
//Keys will be preserved by array_filter
$foundcols = array_filter($colval, 'is_over');
$foundrows = array_filter($rowval, 'is_over');
You still have to calculate the average distance though.

Categories