$a = array('a','b','c','d','e','f');
$b = array('1','2');
$count = 0;
$d = 0 ;
$input = array('ina', 'inb','inc');
foreach ($a as $key => $v) {
$count++;
echo $v;
echo $input[$key];
if ($count%3 == 0){
echo $b[$d++];
reset($input);
}
}
I want like this output
1
a-ina
b-inb
c-inc
2
d-ina
e-inb
f-inc
Actually I want $input two times in a foreach loop. $a have 6 items $input have 3 items and $b have 2 items. I need
To make it more applicable, Demo
$a = array('a','b','c','d','e','f');
$input = array('ina', 'inb','inc');
$loop = 1;
$input_length = count($input); // TODO process the length with 0 case.
foreach($a as $index => $value){
if(!($i = $index % $input_length)){
echo $loop . PHP_EOL;
$loop++;
}
echo $value . "_" . $input[$i] . PHP_EOL;
}
You're keeping a few variables that you don't really need as they can be derived from the $key value from $a. To get the output you want, you could do this:
$a = array('a','b','c','d','e','f');
$b = array('1','2');
$input = array('ina', 'inb','inc');
$len = count($input);
foreach ($a as $key => $v) {
$idx = $key % $len;
if ($idx == 0){
echo $b[floor($key/3)] . PHP_EOL;
}
echo $v . "-";
echo $input[$idx] . PHP_EOL;
}
Output:
1
a-ina
b-inb
c-inc
2
d-ina
e-inb
f-inc
Demo on 3v4l.org
Related
I have these for loop to determine consecutive number. What I achieve so far is to print the output in string.
$arr = [1,2,3,6,11,5,4,8,9,3];
for($start=0; $start<=count($arr); $start++){
for($end=$start+1; $end<=count($arr); $end++){
$total = $arr[$end] - $arr[$start];
if($total == 1){
echo 'Number is '.$arr[$start].','.$arr[$end].'<br/>';
} else {
echo '';
}
$arr[$start++];
}
}
My goal is to add the output into array.
I tried to use multidimensional array but no output display.
$arr = [1,2,3,6,11,5,4,8,9,3];
$arr3 = [];
for($start=0; $start<=count($arr); $start++){
for($end=$start+1; $end<=count($arr); $end++){
$total = $arr[$end] - $arr[$start];
if($total == 1){
$arr2 = array();
$arr2[] = $arr[$start].','.$arr[$end].'';
$arr3[] = $arr2;
} else {
}
$arr[$start++];
}
}
echo '<pre>';
print_r($arr3);
echo '</pre>';
exit;
Appreciate if someone can help me. Thanks.
you can simply use array functions, if sorting is important to you as #nice_dev said, you must sort your array before.
$arr = [1,2,3,6,11,5,4,8,9,3];
$cons = [] ;
while (array_key_last($arr) != key($arr)) {
if ((current($arr)+1) == next($arr)) {
prev($arr);
$cons[] = current($arr) . ',' . next($arr);
}
}
print_r($cons);
the output will be :
Array
(
[0] => 1,2
[1] => 2,3
[2] => 8,9
)
You can better sort() the input array first. This way, collecting all consecutive elements would get much simpler. If value at any index isn't +1 of the previous one, we add the $temp in our $results array and start a new $temp from this index.
Snippet:
<?php
$arr = [1,2,3,6,11,5,4,8,9,3];
$result = [];
sort($arr);
$temp = [];
for($i = 0; $i < count($arr); ++$i){
if($i > 0 && $arr[ $i ] !== $arr[$i - 1] + 1){
$result[] = implode(",", $temp);
$temp = [];
}
$temp[] = $arr[$i];
if($i === count($arr) - 1) $result[] = implode(",", $temp);
}
print_r($result);
Online Demo
I have 2 ranges I am currently looping through.
$arr1 = range(1500, 1505);
$start = 1;
$end = 10;
foreach ($arr1 as $block) {
for ($i = $start; $i <= $end; $i++) {
echo $block . $i; // output -> 15001,15002,15003 ... 15011, 15012 ...
}
}
Is there an easier / more efficient way to do this?
I believe you can do it like this:
for($start = 15001; $start < 15061 ; $start = $start + 10 ) {
$arr = range($start, $start + 8);
$arr[] = $start * 10;
echo implode(" ", $arr) . PHP_EOL;
}
However, I still not get the pattern you trying the create...
Another slightly more efficient approach would be to create the entire range at once. Then use modulo to determine the values divisible by 10, and use mathematics to output the desired alternative value.
Example: https://3v4l.org/L10Jq
foreach (range(15001, 15060) as $v) {
if (0 === $v % 10) {
echo ($v - 9) * 10 . \PHP_EOL;
} else {
echo $v . ' ';
}
}
Result:
15001 15002 15003 15004 15005 15006 15007 15008 15009 150010
15011 15012 15013 15014 15015 15016 15017 15018 15019 150110
15021 15022 15023 15024 15025 15026 15027 15028 15029 150210
15031 15032 15033 15034 15035 15036 15037 15038 15039 150310
15041 15042 15043 15044 15045 15046 15047 15048 15049 150410
15051 15052 15053 15054 15055 15056 15057 15058 15059 150510
To create a single array, pass the value $v by-reference, remove the echo calls and re-assign the value in the conditional.
$ar = range(15001, 15060);
foreach ($ar as &$v) {
if (0 === $v % 10) {
$v = ($v - 9) * 10;
}
}
This question already has answers here:
How to find first array element with value greater than X in PHP?
(2 answers)
Closed 1 year ago.
Say, there is an array and a number:
$values = ['a'=>10, 'b'=>20, 'c'=>30];
$num = 25;
How can I find an index of the array element the value of which is less than the number?
In the above example it will be the 'b' index of which is 1.
You could sort the array by the values then loop through it until a number is hit above the $num. Here is a quick example:
$values = ['a'=>10, 'b'=>20, 'c'=>30];
$num = 25;
$sortedValues = $values;
asort($sortedValues);
while (($current = current($sortedValues)) !== false && $current < $num) {
$lastValue = key($sortedValues);
next($sortedValues);
}
echo $lastValue;
I got it:
$values = ['a'=>1, 'b'=>20, 'c'=>30, 'd'=>40, 'e'=>50];
$num = 55;
$i = null;
foreach ($values as $k => $v){
if ($v == $num){
echo $v;
break;
}
elseif ($num >= 1 && $v > $num){
echo $values[$i];
break;
}
elseif ($num > end($values)){
echo end($values);
break;
}
$i = $k;
}
May be array_filter can be some more handy:
$values = ['a'=>1, 'b'=>20, 'c'=>30, 'd'=>40, 'e'=>50];
$num = 45;
// filter items less than $num
$lesser = array_filter($values, function($v) use($num) {
return $v < $num;
});
// get necessary item/index from filtered, last for example
$lesserKeys = array_keys($lesser);
$lastOfLessKey = end($lesserKeys);
$lastOfLess = end($lesser);
var_dump($lastOfLessKey, $lastOfLess); // d 40
$values = ['a'=>10, 'b'=>20, 'c'=>30];
$num = 25;
foreach($value as $key => $val){
if( (int) $val == (int) $num){
echo 'this is what you are searching. key is: '.$key.', value is: '.$val;
}
}
Here is my code. I don't understand why am I in endless loop.
I think $check has to stop the loop when I make unique random values for my array.
<?php
$foo["blue"] = 0;
$foo["black"] = 0;
$foo["red"] = 0;
$foo["white"] = 0;
$check;
do
{
foreach($foo as &$val)
{
$val = rand(1,6);
}
$foo = array_unique($foo);
$check = count($foo);
}
while($check != 4);
echo '............................ <br>';
foreach($foo as $key=>$value)
{
echo $key . ' ' . $value . '<br>';
}
?>
The problem is that the first time through the loop there are some duplicates, so array_unique() reduces the array from 4 elements to 1, 2, or 3. The foreach loop can never make the array bigger again, because it's only looping over the elements that currently exist in the array. So once the array shrinks, it will never grow back to 4 elements, and $check != 4 will always be true.
You should get the original keys of the array and use that.
<?php
$foo["blue"] = 0;
$foo["black"] = 0;
$foo["red"] = 0;
$foo["white"] = 0;
$keys = array_keys($foo);
$check;
do
{
foreach($keys as $i)
{
$foo[$i] = rand(1,6);
}
$foo = array_unique($foo);
$check = count($foo);
}
while($check != 4);
echo '............................ <br>';
foreach($foo as $key=>$value)
{
echo $key . ' ' . $value . '<br>';
}
?>
DEMO
Personally, I wouldn't do it in a loop with such low entropy as it could take all day to finally match a random set.
A better way would be to generate a range and randomise that, then loop over your array and set the value.
<?php
$rand = range(1, 6);
shuffle($rand);
$foo["blue"] = 0;
$foo["black"] = 0;
$foo["red"] = 0;
$foo["white"] = 0;
$i=0;
foreach ($foo as $key => $value) {
$foo[$key] = $rand[$i];
$i++;
}
print_r($foo);
/*Array
(
[blue] => 1
[black] => 3
[red] => 2
[white] => 5
)
*/
https://3v4l.org/4hPku
Instead of just 1, how can I pick the 4 highest values from an array using max()?
You could use an SplMaxHeap
function maxN(array $numbers, $n)
{
$maxHeap = new SplMaxHeap;
foreach($numbers as $number) {
$maxHeap->insert($number);
}
return iterator_to_array(
new LimitIterator($maxHeap, 0, $n)
);
}
Usage (demo):
print_r( maxN( array(7,54,2,4,26,7,82,4,34), 4 ) );
You could try this:
$a = array(3,5,6,1,23,6,78,99);
asort($a);
var_dump(array_slice($a, -4));
HTH.
This will do it in Θ(n) time:
$a = $b = $c = $d = null;
foreach($array as $v) {
if(!isset($a) || $v > $a) {
$d = $c;
$c = $b;
$b = $a;
$a = $v;
}elseif(!isset($b) || $v > $b) {
$d = $c;
$c = $b;
$b = $v;
}elseif(!isset($c) || $v > $c) {
$d = $c;
$c = $v;
}elseif(!isset($d) || $v > $d) {
$d = $v;
}
}
$result = array($a, $b, $c, $d);
function maxs($ar, $count=4)
{
$res = array();
foreach ($ar as $v)
{
for ($i = 0;$i < $count;$i++)
{
if ($i >= count($res) || $v > $res[$i])
{
do
{
$tmp = $res[$i];
$res[$i] = $v;
$v = $tmp;
$i++;
}
while ($i < $count);
break;
}
}
}
return $res;
}
A simple method using php predefined functions.
<?php
$arr = array(6, 8, 3, 2, 7, 9);
rsort($arr);
$first = array_shift($arr);
$second = array_shift($arr);
$third = array_shift($arr);
echo $first; // print 9
echo $second; // print 8
echo $third; // print 7
?>
While storing itself you can maintain another array as soon as the new item is inserted check with the max value in the inner array if the item being inserted is greater insert this item. During the item pop do viceversa. From the inner maintained array you can get as many max numbers as possible.