Interchange the display order in a loop - php

I am trying to interchange the display order in a loop.
For example i have an array $array with values: 1,2,3,4,5 and want to display the result in the order 2,1,3,4,5.
I am using the following code for the purpose and which worked for me:
<?php
$array = array(
1,
2,
3,
4,
5,
);
$tempArray = array();
$count = 1;
foreach($array as $key => $value){
$tempArray[$key] = $value;
if(in_array($count, array(1, 2))){
if($count == 2){
echo $tempArray[1] . '<br />';
echo $tempArray[0] . '<br />';
}
}else{
echo $value . '<br />';
}
$count++;
}
But i would like to know if there is any effective (better) way of doing so?
EDIT:
$array = array(
1,
2,
3,
4,
5,
);
//Either
/*$temp = $array[1];
$array[1] = $array[0];
$array[0] = $temp;*/
//OR
list($array[1], $array[0]) = array($array[0], $array[1]);
foreach($array as $key => $value){
echo $value . '<br />';
}
Either way works fine with minimum code.
Thank you guys!

To change the display order of $array that is array(1, 2, 3, 4, 5) without changing the order of the elements in $array you need to define the display order and then display based on the display order:
$array = array(1, 2, 3, 4, 5);
$display = array_keys($array);
list($display[1], $display[0]) = array($display[0], $display[1]);
foreach ($display as $key)
{
$value = $array[$key];
printf("%d<br />\n", $value);
}
This works - as you wrote it already yourself in the comments - by switching the order (keys) of the first two elements(0 and 1, arrays are zero-based).

Related

PHP loop through array with condition

I have a loop which i made like this:
$arr = array(1, 2, 3, 4, 5, 6, 7);
foreach ($arr as &$value) {
echo $value;
}
My loop result shows this:
1234567
I would like this to only show the numbers 1 to 4.
And when it reaches 4 it should add a break and continue with 5671.
So an example is:
1234<br>
5671<br>
2345<br>
6712<br>
I have to make this but I have no idea where to start, all hints/tips are very welcome or comment any direction I should Google.
Here is more universal function- you can pass an array as argument, and amount of elements you want to display.
<?php
$array = array(1,2,3,4,5,6,7);
function getFirstValues(&$array, $amount){
for($i=0; $i<$amount; $i++){
echo $array[0];
array_push($array, array_shift($array));
}
echo "<br />";
}
getFirstValues($array, 4);
getFirstValues($array, 4);
getFirstValues($array, 4);
getFirstValues($array, 4);
?>
The result is:
1234
5671
2345
6712
This produces the exact results you want
$arr = array(1, 2, 3, 4, 5, 6, 7);
$k=0;
for($i=1;$i<=5;++$i){
foreach ($arr as &$value) {
++$k;
echo $value;
if($k %4 == 0) {
echo '<br />';
$k=0;
}
}
}
You are looking for array_chunk()
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
$chunks = array_chunk($arr, 4);
foreach ($chunks as $array) {
foreach ($array as $value) {
echo $value;
}
echo "<br />";
}
The output is:
1234
5678
9101112
13

PHP array doubling digits

I have an array and I want to double it but after executing the array doesn't change how to correct it as minimally as possible.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
$value = $value * 2;
}
?>
Your values didn't double because you're not saying the key should be overwritten in $arr this code should be working:
$arr = array(1,2,3,4);
foreach($arr as $key => $value){
$arr[$key] = $value*2;
}
An alternative would be to use array_map().
<?php
function double($i){
return $i*2;
}
$arr = array(1, 2, 3, 4);
$arr = array_map('double', $arr);
var_dump($arr);
?>
You need to double the actual array $arr element, not just the value in the cycle.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $key => $value) {
$arr[$key] = $value * 2;
}
?>
You are using a variable $value which is assigning in each for loop so this value stored in $value is overwrithing in your foreach loop. You have
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
$value = $value * 2;
}
?>
This will work
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
print_r($arr);
?>
short solution, and supported in < PHP 5.3, try this code
<?php
$arr = array(1, 2, 3, 4);
$arr = array_map(create_function('$v', 'return $v * 2;'), $arr);
print_r($arr);
DEMO
Try the following code:
$arr = array(1, 2, 3, 4);
array_walk($arr, function(&$item){
$item*=2;
});
var_dump($arr);

Remove duplicates of array

I was just going through these questions for PHP and got stuck at one of them. The question is:
You have a PHP 1 dimensional array. Please write a PHP function that
takes 1 array as its parameter and returns an array. The function must
delete values in the input array that shows up 3 times or more?
For example, if you give the function
array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9)the function will returnarray(1, 3, 5, 2, 3, 1, 9)
I was able to check if they are repeating themselves but I apply it to the array I am getting as input.
function removeDuplicate($array){
$result = array_count_values( $array );
$values = implode(" ", array_values($result));
echo $values . "<br>";
}
$qArray = array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
removeDuplicate($qArray);
One more thing, we cannot use array_unique because it includes the value which is repeated and in question we totally remove them from the current array.
Assuming the value may not appear 3+ times anywhere in the array:
$array = array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
// create array indexed by the numbers to remove
$remove = array_filter(array_count_values($array), function($value) {
return $value >= 3;
});
// filter the original array
$results = array_values(array_filter($array, function($value) use ($remove) {
return !array_key_exists($value, $remove);
}));
If values may not appear 3+ times consecutively:
$results = [];
for ($i = 0, $n = count($array); $i != $n;) {
$p = $i++;
// find repeated characters
while ($i != $n && $array[$p] === $array[$i]) {
++$i;
}
if ($i - $p < 3) {
// add to results
$results += array_fill(count($results), $i - $p, $array[$p]);
}
}
This should work :
function removeDuplicate($array) {
foreach ($array as $key => $val) {
$new[$val] ++;
if ($new[$val] >= 3)
unset($array[$key]);
}
return $array;
}
run this function i hope this help..
function removeDuplicate($array){
$result = array_count_values( $array );
$dub = array();
$answer = array();
foreach($result as $key => $val) {
if($val >= 3) {
$dub[] = $key;
}
}
foreach($array as $val) {
if(!in_array($val, $dub)) {
$answer[] = $val;
}
}
return $answer;
}
You can use this function with any number of occurrences you want - by default 3
function removeDuplicate($arr, $x = 3){
$new = $rem = array();
foreach($arr as $val) {
$new[$val]++;
if($new[$val]>=$x){
$rem[$val]=$new[$val];
}
}
$new = array_keys(array_diff_key($new, $rem));
return $new;
}
I think it is getting correct output. just try once.
$array=array(1,2,3,7,4,4,3,5,5,6,7);
$count=count($array);
$k=array();
for($i=0;$i<=$count;$i++)
{
if(!in_array($array[$i],$k))
{
$k[]=$array[$i];
}
}
array_pop($k);
print_r($k);
in this first $k is an empty array,after that we are inserting values into $k.
You should use array_unique funciton.
<?php
$q = array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
print_r(array_unique($q));
?>
Try it and let me know if it worked.

How to count array values and keep only the ones that are relevant?

I have an array that contains multiple integers, I'm interested only in integers that repeat themselves a certain number of times. For example:
$items = (0, 0, 0, 1, 1, 2, 3, 3, 3)
I want to know which item(s) are repeated exactly $number (in this example $number = 3) times (in this example new array $items = (0, 3)).
If none of the array items is repeated $number times, I need to have var $none = 1.
I know for a function array_count_values but don't know how to implement it to my case...
$number = 3;
$items = array_keys(array_filter(array_count_values($items), create_function('$n', "return \$n == $number;")));
if (!$items) {
$none = 1;
}
use array_count_values to get a pairing of how often each number occurs
filter this through an array_filter callback that discards all entries except those that have a count of $number
take the keys of the resulting array (the actual counted values)
the resulting array is either empty or contains the values that occur $number of times
I know there are a lot of solutions, but thought I'd add one more. ;-)
function array_repeats($items,$repeats,&$none){
$result = array();
foreach (array_unique($items) as $item){
$matches = array_filter($items,create_function('$a','return ($a=='.$item.');'));
if (count($matches) == $repeats)
$result[] = $item;
}
$none = (count($result)?1:0);
return $result;
}
DEMO
$repeated_items will be an array containing only your desired items.
$limit = 3; //your limit for repetition
$catch = array();
foreach ($items as $item){
if(array_key_exists($item, $catch)){
$catch[$item]++;
} else {
$catch[$item] = 1;
}
}
$repeated_items = array();
foreach ($catch as $k=>$caught){
if($caught>=$limit){
$repeated_items[]=$k;
}
}
Some pseudo-code to get you started:
Sort your array in order to get similar items together
Foreach item
if current item == previous item then
repeat count ++
else
if repeat count > limit then
add current item to new array
$items = array(0, 0, 0, 1, 1, 2, 3, 3, 3);
$count = array_count_values($items);
$number = 3;
$none = 1;
$result = array();
foreach(array_unique($items) as $item) {
if($count[$item] == $number) {
$result[] = $item;
$none = 0;
}
}
$items = array(0, 0, 0, 1, 1, 2, 3, 3, 3);
$none=1;
$new_array=array();
$n=3;
dojob($items,$n,$none,$new_array);
function dojob($items,$n,&$none,&$new_array)
{
$values_count=array_count_values($items);
foreach($values_count as $value => $count)
{
if($count ==$n)
{
$none=0;
$new_array[]=$value;
}
}
}
A bit late, but:
<?php
$items = array(0, 0, 0, 1, 1, 2, 3, 3, 3);
$temp = array_unique($items);
$result = array();
$none = 1;
$number = 3;
foreach($temp as $tmp)
{
if(count(array_keys($items, $tmp)) == $number)
{
array_push($result,$tmp);
$none = 0;
}
}
print_r($result);
?>
$items = array(0, 0, 0, 1, 1, 2, 3, 3, 3);
$icnt = array_count_values($items);
function eq3($v) {
return $v==3;
}
var_export(array_filter($icnt, 'eq3'));
will produce array ( 0 => 3, 3 => 3, ). In your example 0 and 3 repeat 3 times. Array_filter is needed here to, actually, filter your resulting array and get rid of necessary values, but you was right about using array_count_values here.
One way would be to create a kind of hash table and loop over every item in your array.
$items = array(0, 0, 0, 1, 1, 2, 3, 3, 3);
$number = 3;
$none = 1;
foreach ($items as $value) {
if ($hash[$value] >= $number) {
# This $value has occured as least $number times. Lets save it.
$filtered_items[] = $value;
# We have at least one item in the $items array >= $number times
# so set $none to 0
$none = 0;
# No need to keep adding
continue;
} else {
# Increment the count of each value
$hash[$value]++;
}
}
$items = $filtered_items;

PHP - when using foreach to loop through array, how can I tell if I'm on the last pair?

I'm trying to 'pretty-print' out an array, using a syntax like:
$outString = "[";
foreach($arr as $key=>$value) {
// Do stuff with the key + value, putting the result in $outString.
$outString .= ", ";
}
$outString .= "]";
However the obvious downside of this method is that it will show a "," at the end of the array print out, before the closing "]". Is there a good way using the $key=>$value syntax to detect if you're on the last pair in the array, or should I switch to a loop using each() instead?
Build up an array, and then use implode:
$parts = array();
foreach($arr as $key=>$value) {
$parts[] = process($key, $value);
}
$outString = "[". implode(", ", $parts) . "]";
You can just trim off the last ", " when for terminates by using substring.
$outString = "[";
foreach($arr as $key=>$value) {
// Do stuff with the key + value, putting the result in $outString.
$outString .= ", ";
}
$outString = substr($outString,-2)."]"; //trim off last ", "
Do the processing separately and then use implode() to join:
$outArr = array();
foreach($arr as $key => $value) {
$outArr[] = process($key, $value);
}
$outString = '[' . implode(', ', $outArr) . ']';
Notwithstanding the circumstances of your example (joining strings with commas, for which implode is the right way to go about it), to answer your specific question, the canonical way to iterate through an array and check if you're on the last element is using CachingIterator:
<?php
$array = array('k'=>'v', 'k1'=>'v1');
$iter = new CachingIterator(new ArrayIterator($array));
$out = '';
foreach ($iter as $key=>$value) {
$out .= $value;
// CachingIterator->hasNext() tells you if there is another
// value after the current one.
if ($iter->hasNext()) {
$out .= ', ';
}
}
echo $out;
It might be easier to do it like this, and add a comma to the string before the item if it isn't the first item.
$first= true;
foreach ($arr as $key => $value) {
if (! $first) {
$outString .=', ';
} else {
$first = false;
}
//add stuff to $outString
}
Is the output format JSON? If so you could consider using json_encode() instead.
You could do it as a normal for loop:
$outString = "[";
for ($i = 0; $i < count($arr); $i++) {
// Do stuff
if ($i != count($arr) - 1) {
$outString += ", ";
}
}
However, the nicest way to do it, IMHO, is storing all the components in an array, and then imploding:
$outString = '[' . implode(', ', $arr) . ']';
implode() takes all elements in an array and puts them together in a string, separated by its first argument.
There are many possibilities. I think this is one of the simplest solutions:
$arr = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g');
echo '[', current($arr);
while ($n = next($arr)) echo ',', $n;
echo ']';
Outputs:
[a,b,c,d,e,f,g]
I tend to avoid using loops in situations such as these. You should use implode() to join lists with a common deliminator and use array_map() to handle any processing on that array before the join. Note the following implementations that should express the versatility of these functions. Array map can take a string (name of a function) representing either a built-in function or user defined function (first 3 examples). You may pass it a function using create_function() or pass a lambda/anonymous function as the first parameter.
$a = array(1, 2, 3, 4, 5);
// Using the user defined function
function fn ($n) { return $n * $n; }
printf('[%s]', implode(', ', array_map('fn', $a)));
// Outputs: [1, 4, 9, 16, 25]
// Using built in htmlentities (passing additional parameter
printf('[%s]', implode(', ', array_map( 'intval' , $a)));
// Outputs: [1, 2, 3, 4, 5]
// Using built in htmlentities (passing additional parameter
$b = array('"php"', '"&<>');
printf('[%s]', implode(', ', array_map( 'htmlentities' , $b, array_fill(0 , count($b) , ENT_QUOTES) )));
// Outputs: ["php", "&<>]
// Using create_function <PHP 5
printf('[%s]', implode(', ', array_map(create_function('$n', 'return $n + $n;'), $a)));
// Outputs: [2, 4, 6, 8, 10]
// Using a lambda function (PHP 5.3.0+)
printf('[%s]', implode(', ', array_map(function($n) { return $n; }, $a)));
// Outputs: [1, 2, 3, 4, 5]

Categories