This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Combing 3 arrays into one array
I have the following arrays:
$front = array("front_first","front_second");
$back = array("back_first", "back_second", "back_third","back_fourth");
what I'm trying to do is merge them so an output like this would result:
$final = array(
"back_first",
"front_first",
"back_second",
"front_second",
"back_third",
"front_second",
"back_fourth",
"front_second"
);
How can I have it repeat the last value in the shortest array so that it can combine into one $final[] with no empty values?.
php's array_merge
$final = array_merge($front, $back);
and maybe a combination with array_pad?
$front = array_pad($front, count($back)-1, 'second_front');
$final = array_merge($front, $back);
The first bit is easy, just use array_merge() to construct your combined array.
The second bit requires arbitrary sorting and therefore will require use of usort() to sort the array according to rules you implement in the callback function.
Is the order really important?
Working Codepad - bgIYz9iw
$final = array();
for( $i = 0; $i < 4; $i++ ) {
if( $i > 1 ) {
$final[] = $back[$i];
$final[] = $front[1];
}
else {
$final[] = $back[$i];
$final[] = $front[$i];
}
}
Related
Given the following array:
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
And assuming $n = 2, what is the most efficient way to get a count of each value in the array within $n of each value?
For example, 6 has 3 other values within $n: 5,7,7.
Ultimately I'd like a corresponding array with simply the counts within $n, like so:
// 0,0,1,2,2,5,6,7,7,9,10,10 // $arr, so you can see it lined up
$count_arr = array(4,4,4,4,4,3,3,4,4,4, 2, 2);
Is a simple foreach loop the way to go? CodePad Link
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
$n = 2;
$count_arr = array();
foreach ($arr as $v) {
$range = range(($v-$n),($v+$n)); // simple range between lower and upper bound
$count = count(array_intersect($arr,$range)); // count intersect array
$count_arr[] = $count-1; // subtract 1 so you don't count itself
}
print_r($arr);
print_r($count_arr);
My last answer was written without fully groking the problem...
Try sorting the array, before processing it, and leverage that when you run through it. This has a better runtime complexity.
$arr = array(0,0,1,2,2,5,6,7,7,9,10,10);
asort($arr);
$n = 2;
$cnt = count($arr);
$counts = array_pad(array(), $cnt, 0);
for ($x=0; $x<$cnt; $x++) {
$low = $x - 1;
$lower_range_bound = $arr[$x]-$n;
while($low >= 0 && ($arr[$low] >= $lower_range_bound)) {
$counts[$x]++;
$low--;
}
$high = $x + 1;
$upper_range_bound = $arr[$x]+$n;
while($high < $cnt && $arr[$high] <= $upper_range_bound) {
$counts[$x]++;
$high++;
}
}
print_r($arr);
print_r($counts);
Play with it here: http://codepad.org/JXlZNCxW
This question already has answers here:
How to get sub array in PHP?
(3 answers)
Closed 9 years ago.
I have an first $array1 of 200 integer values,$array1 integer values are random values and second array say as below
$array2= array('30','40,'70','30','30');
Both the arrays are generating dynamically.
I want to divide my $array1 into smaller arrays as per $array2 values, as first 30 integers from $array1 will make separate array, later 40 intergers from $array1 will make second new array and so on. From above example there will be 5 new arrays.
Can anyone please help me.
I tried below below it can just divide based on values assigned. But it is not useful
$arrays = array_chunk($array1, 30);
You should iterate over the array of chunk sizes and cut off an appropriate portion of your input array each time:
$input = range(0, 199);
$chunks = array(30, 40, 70, 30, 30);
$output = array();
$processed = 0;
while($chunks) {
$processed += $size = array_shift($chunks);
$output[] = array_slice($input, $processed, $size);
}
Why do not you try this
$startingPoint = 0;
foreach($array2 as $val)
{
for($i = $startingPoint ; $i < $startingPoint + $val ; $i++)
{ $array1[$i] }
$startingPoint += $val
}
This question already has answers here:
Removing a value from a PHP Array
(3 answers)
Closed 8 years ago.
I have an array that looks like this
$hours_worked = array('23',0,'24',0)
What want to do is to loop through the array and remove the element that contains 0
What I have so far is:
for($i = 0; $i < count($hours_worked); $i++)
{
if($hours_worked[$i] === 0 )
{
unset($hours_worked[$i]);
}
}
However the result I get is $hours_worked = array(23,24,0). I.e. it does not remove the final element from the array. Any ideas?
The problem with this code is that you are calculating count($hours_worked) on each iteration; once you remove an item the count will decrease, which means that for each item removed the loop will terminate before seeing one item at the end of the array. So an immediate way to fix it would be to pull the count out of the loop:
$count = count($hours_worked);
for($i = 0; $i < $count; $i++) {
// ...
}
That said, the code can be further improved. For one you should always use foreach instead of for -- this makes the code work on all arrays instead of just numerically indexed ones, and is also immune to counting problems:
foreach ($hours_worked as $key => $value) {
if ($value === 0) unset($hours_worked[$key]);
}
You might also want to use array_diff for this kind of work because it's an easy one-liner:
$hours_worked = array('23',0,'24',0);
$hours_worked = array_diff($hours_worked, array(0)); // removes the zeroes
If you choose to do this, be aware of how array_diff compares items:
Two elements are considered equal if and only if (string) $elem1 ===
(string) $elem2. In words: when the string representation is the
same.
Try foreach loops instead
$new_array = array();
foreach($hours_worked as $hour) {
if($hour != '0') {
$new_array[] = $hour;
}
}
// $new_array should contain array(23, 24)
This question already has answers here:
Count number of values in array with a given value
(8 answers)
Closed 3 years ago.
I have an array named $uid. How can I check to see how many times the value "12" is in my $uid array?
Several ways.
$cnt = count(array_filter($uid,function($a) {return $a==12;}));
or
$tmp = array_count_values($uid);
$cnt = $tmp[12];
or any number of other methods.
Use array_count_values(). For example,
$freqs = array_count_values($uid);
$freq_12 = $freqs['12'];
Very simple:
$uid= array(12,23,12,4,2,5,56);
$indexes = array_keys($uid, 12); //array(0, 1)
echo count($indexes);
Use the function array_count_values.
$uid_counts = array_count_values($uid);
$number_of_12s = $uid_counts[12];
there are different solution to this:
$count = count(array_filter($uid, function($x) { return $x==12;}));
or
array_reduce($uid, function($c, $v) { return $v + ($c == 12?1:0);},0)
or just a for loop
for($i=0, $last=count($uid), $count=0; $i<$last;$i++)
if ($uid[$i]==12) $count++;
or a foreach
$count=0;
foreach($uid as $current)
if ($current==12) $count++;
$repeated = array();
foreach($uid as $id){
if (!isset($repeated[$id])) $repeated[$id] = -1;
$repeated[$id]++;
}
which will result for example in
array(
12 => 2
14 => 1
)
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to find the repeating elements in an array?
If I have this array : array("hey", "test", "hey");
And I want to count how many times I have the word "hey", how can I do that?
Wouldn't it be great if there were a function like array_count_values?
</sarcasm>
Some example code of usage:
$arr = array(...);
$valCounts = array_count_values( $arr );
echo $valCounts['hey'];
I highly recommend browsing php.net and, in-particular, learning the array functions.
$count = 0;
foreach($array as $item) {
if($item == 'hey') {
$count++;
}
}
print $count;
The command is array_count_values. Check
http://www.php.net/manual/en/function.array-count-values.php
You just need to loop over the array.
$x = 0;
foreach (array("hey","test","hey") as $value) {
if ($value === "hey") $x++;
}
For a less efficient, but shorter, solution, you could use array_count_value.
$counts = array_count_values(array("hey","test","hey"));
$x = $counts["hey"];