I check the equality of all values in the array in php this way. I could not find how to do this on any web page, if there is an easier method you can write.
$array = array(2, 2, 1);
$first_value = $array[0];
$count_invoice = count($array);
$i = 0;
foreach ($array as $item) {
if ($item == $first_value) {
$i++;
} else {
// Not equal.
}
}
if ($i == $count_invoice) {
echo "Array equal.";
} else {
echo "Array not equal.";
}
There's no need to count anything. As soon as you see the value, which not equals $first_value, you can break the loop:
$array = array(2, 2, 2);
$first_value = array_shift($array);
$allEquals = true;
foreach ($array as $item) {
if ($item != $first_value) {
$allEquals = false;
break;
}
}
if ($allEquals) {
echo "Array equal.";
} else {
echo "Array not equal.";
}
Good job on finding a solution yourself. However, your code is a little convoluted and might be simplified. I understand you don't have an actual question, but you may find my suggested improvement useful anyway.
<?php
// Your input array.
$array = array(2, 1, 1);
// Another array, which consists of unique elements.
$uniqueArray = array(1, 1, 1);
// Use array_unique() to remove duplicates, and count the results. If there is more than one value, then the array didn't consist of all unique values.
var_dump(count(array_unique($array)) === 1); // FALSE
var_dump(count(array_unique($uniqueArray)) === 1); // TRUE
Related
lets suppose that I have an Array;
$array = [1, 2, "Mohcin", "Mohammed", 3,];
I can Access this array and skip the items "Mohcin" and "Mohammed" inside the iteration using for or foreach loop and continue.. but my question how I can count the number of items that I skipped inside the loop? and that is "TWO" in this case.
Thanks in advance
$array = [1, 2, "Mohcin", "Mohammed", 3,];
$skipped = 0;
foreach ($array as $element) {
if ($someCondition) {
// Remove the element
$skipped++;
}
}
// You access $skipped here
You can do it even without a foreach loop.
$array = [1, 2, "Mohcin", "Mohammed", 3,];
$skip = ["Mohcin", "Mohammed"];
$diff = array_diff($array, $skip);
$skipCount = count($array) - count($diff);
echo $skipCount; // prints 2
But if you want with foreach for the reason of more complex logic, do like this
$skipCount = 0;
foreach($array as $value) {
if($value === "Mohcin" || $value === "Mohammed") {
$skipCount++;
continue;
}
// Do anything else when not skipped
}
echo $skipCount; // prints 2
You need to create variable that keeps count of skips every time you skip value.
$skips = 0;
for($counter = 0; $counter < count($array); $counter++) {
if(skip) {
$skips++;
continue;
}
}
I want to combine two arrays into a dictionary.
The keys will be the distinct values of the first array, the values will be all values from the second array, at matching index positions of the key.
<?php
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
?>
array_combine($b,$a);
Expected result as
<?php
/*
Value '1' occurs at index 0, 1 and 4 in $b
Those indices map to values 2, 3 and 6 in $a
*/
$result=[1=>[2,3,6],3=>4,2=>[5,7],6=>8,8=>[9,10]];
?>
There are quite a few PHP array functions. I'm not aware of one that solves your specific problem. you might be able to use some combination of built in php array functions but it might take you a while to weed through your choices and put them together in the correct way. I would just write my own function.
Something like this:
function myCustomArrayFormatter($array1, $array2) {
$result = array();
$num_occurrences = array_count_values($array1);
foreach ($array1 AS $key => $var) {
if ($num_occurrences[$var] > 1) {
$result[$var][] = $array2[$key];
} else {
$result[$var] = $array2[$key];
}
}
return $result;
}
hope that helps.
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
$results = array();
for ($x = 0; $x < count($b); $x++) {
$index = $b[$x];
if(array_key_exists ($index, $results)){
$temp = $results[$index];
}else{
$temp = array();
}
$temp[] = $a[$x];
$results[$index] = $temp;
}
print_r($results);
Here's one way to do this:
$res = [];
foreach ($b as $b_index => $b_val) {
if (!empty($res[$b_val])) {
if (is_array($res[$b_val])) {
$res[$b_val][] = $a[$b_index];
} else {
$res[$b_val] = [$res[$b_val], $a[$b_index]];
}
} else {
$res[$b_val] = $a[$b_index];
}
}
var_dump($res);
UPDATE: another way to do this:
$val_to_index = array_combine($a, $b);
$result = [];
foreach ($val_to_index as $value => $index) {
if(empty($result[$index])){
$result[$index] = $value;
} else if(is_array($result[$index])){
$result[$index][] = $value;
} else {
$result[$index] = [$result[$index], $value];
}
}
var_dump($result);
I have an array given below
$array = array(50,51,52,53,54,55,56,57,58,59);
I am trying to print the values of array while even numbers will remain in same order and the odd numbers are sorted i.e. 59,57,55,53,51
The output should be like
50,59,52,57,54,55,56,53,58,51
I've separated the even and odd numbers in two diff variables. how should i proceed further ?
here is my code
$even= "";
$odd= "";
for($i=50;$i<=59;$i++)
{
if($i%2==0)
{
$even.=$i.",";
}else $odd.=$i.",";
}
echo $even.$odd;
Instead of pushing the evens and odds into a string, push them each into an array, sort the array with the odds in reverse and then loop through one of them (preferably through the even array) and add the even and the odd to a new array.
This is how I've done it:
$array = array(50,51,52,53,54,55,56,57,58,59);
$odds = array();
$even = array();
foreach($array as $val) {
if($val % 2 == 0) {
$even[] = $val;
} else {
$odds[] = $val;
}
}
sort($even);
rsort($odds);
$array = array();
foreach($even as $key => $val) {
$array[] = $val;
if(isset($odds[$key])) {
$array[] = $odds[$key];
}
}
https://3v4l.org/2hW6T
But you should be cautious if you have less even than odd numbers, as the loop will finish before all odds are added. You can check for that either before or after you've filled the new array. If you check after filling the new array, you can use array_diff and array_merge to add the missing odds to the new array.
http://php.net/array_diff http://php.net/array_merge
Following code will run as per the odd number count. There won't be any loop count issue.
function oddNumber($num){
return $num % 2 == 1;
}
$givenArray = array(50, 51, 52, 53, 54, 55, 56, 57, 58, 59);
$oddArray = array_filter($givenArray, "oddNumber");
rsort($oddArray);
$finalArray = array();
$oddCount = 0;
foreach($givenArray as $num){
if(oddNumber($num)){
$finalArray[] = $oddArray[$oddCount];
++$oddCount;
}else{
$finalArray[] = $num;
}
}
print_r($finalArray);
I'm trying to work out how to continuously loop through an array, but apparently using foreach doesn't work as it works on a copy of the array or something along those lines.
I tried:
$amount = count($stuff);
$last_key = $amount - 1;
foreach ($stuff as $key => $val) {
// Do stuff
if ($key == $last_key) {
// Reset array cursor so we can loop through it again...
reset($stuff);
}
}
But obviously that didn't work. What are my choices here?
An easy way is to combine an ArrayIterator with an InfiniteIterator.
$infinite = new InfiniteIterator(new ArrayIterator($array));
foreach ($infinite as $key => $val) {
// ...
}
You can accomplish this with a while loop:
while (list($key, $value) = each($stuff)) {
// code
if ($key == $last_key) {
reset($stuff);
}
}
This loop will never stop:
while(true) {
// do something
}
If necessary, you can break your loop like this:
while(true) {
// do something
if($arbitraryBreakCondition === true) {
break;
}
}
Here's one using reset() and next():
$total_count = 12;
$items = array(1, 2, 3, 4);
$value = reset($items);
echo $value;
for ($j = 1; $j < $total_count; $j++) {
$value = ($next = next($items)) ? $next : reset($items);
echo ", $value";
};
Output:
1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4
I was rather surprised to find no such native function. This is a building block for a Cartesian product.
You could use a for loop and just set a condition that's always going to be true - for example:
$amount = count($stuff);
$last_key = $amount - 1;
for($key=0;1;$key++)
{
// Do stuff
echo $stuff[$key];
if ($key == $last_key) {
// Reset array cursor so we can loop through it again...
$key= -1;
}
}
Obviously, as other's have pointed out - make sure you've got something to stop the looping before you run that!
Using a function and return false in a while loop:
function stuff($stuff){
$amount = count($stuff);
$last_key = $amount - 1;
foreach ($stuff as $key => $val) {
// Do stuff
if ($key == $last_key) {
// Reset array cursor so we can loop through it again...
return false;
}
}
}
while(stuff($stuff)===FALSE){
//say hello
}
Let's say I have an array like this:
$my_array = array(1, 2, 3, 4, array(11, 12, 13, 14), 6, 7, 8, array(15, 16, 17, 18), 10);
I want to build a recursive function that returns an array which contains all the even numbers from my_array. I tried something like:
function get_even_numbers($my_array)
{
$even_numbers = array();
foreach($my_array as $my_arr)
{
if(is_array($my_arr)
{
get_even_numbers($my_arr);
foreach($my_arr as $value)
{
if($value % 2 == 0)
{
$even_numbers[] = $value;
}
}
}
}
return even_numbers;
}
But it doesn't works.
Thank you
It's simple:
Check if the input you get into the function is an array.
If it is, that means you have to loop over the values of the array, and call your function (so it is recursive)
Otherwise, just check if the value coming in is even, and add it to an array to return.
That, in PHP, looks like:
function recursive_even( $input) {
$even = array();
if( is_array( $input)) {
foreach( $input as $el) {
$even = array_merge( $even, recursive_even( $el));
}
}
else if( $input % 2 === 0){
$even[] = $input;
}
return $even;
}
Unless it is a thought exercise for your own edification, implementing a recursive function isn't required for this task, which can accomplished instead by using the higher-order, built-in PHP function, array_walk_recursive.
$res = array();
array_walk_recursive($my_array, function($a) use (&$res) { if ($a % 2 == 0) { $res[] = $a; } });
Of course, this could be wrapped in a function:
function get_even_numbers($my_array) {
$res = array();
array_walk_recursive($my_array, function($a) use (&$res) { if ($a % 2 == 0) { $res[] = $a; } });
return $res;
}