Getting specidic values from PHP arrays - php

Is there a way to get the first value from array, then the first value key + 3 ; then +6 then + 9 ans so on
Take this array for example,
array(1,2,5,14,19,2,11,3,141,199,52,24,16)
i want extract a value every 3 so the result would be
array(1,14,11,199,16)
Can i do that with existing PHP array function?

Use a for loop and increment the counter variable by 3.
for ($i = 0; $i <= count(your array); $i+3) {
echo $myarray[i]
}

The following is function that will handle extracting the values from a given array. You can specify the number of steps between each value and if the results should use the same keys as the original. This should work with regular and associative arrays.
<?php
function extractValues($array, $stepBy, $preserveKeys = false)
{
$results = array();
$index = 0;
foreach ($array as $key => $value) {
if ($index++ % $stepBy === 0) {
$results[$key] = $value;
}
}
return $preserveKeys ? $results : array_values($results);
}
$array = array(1, 2, 5, 14, 19, 2, 11, 3, 141, 199, 52, 24, 16);
$assocArray = array('a' => 1, 'b' => 2, 'c' => 5, 'd' => 14, 'e' => 19, 'f' => 2, 11, 3, 141, 199, 52, 24, 16);
print_r(extractValues($array, 3));
print_r(extractValues($array, 3, true));
print_r(extractValues($assocArray, 5));
print_r(extractValues($assocArray, 5, true));
?>
Output
Array
(
[0] => 1
[1] => 14
[2] => 11
[3] => 199
[4] => 16
)
Array
(
[0] => 1
[3] => 14
[6] => 11
[9] => 199
[12] => 16
)
Array
(
[0] => 1
[1] => 2
[2] => 52
)
Array
(
[a] => 1
[f] => 2
[4] => 52
)

Use a loop and check the key.
$result = array();
foreach($array as $key => $value) {
if ($key % 3 === 0) {
$result[] = $value;
}
}

Try below one:
<?php
$your_array = array (1,2,5,14,19,2,11,3,141,199,52,24,16);
$every_3 = array();
$i = 0;
foreach($your_value as $value) {
$i++;
if($i%3==0){
$every_3[]=$value;
}
}
var_dump($every_3);
?>

Do like this
$arr=array (1,2,5,14,19,2,11,3,141,199,52,24,16);
$narr=array();
for($i=0;$i<count($arr);$i=$i+3){
$narr[]=$arr[$i]
}
print_r($narr);

<?php
$mynums = array(1,2,5,14,19,2,11,3,141,199,52,24,16);
foreach ($mynums as $key => $value) {
if ( $key % 3 === 0)
{
$newnum[] = $value;
}
}
var_dump($newnum);
?>

$data = array(1,2,5,14,19,2,11,3,141,199,52,24,16);
$matches = array();
foreach($data as $key => $value)
{
if($key%3 === 0)
{
$matches[] = $value;
}
}
var_dump($matches);

The only way you could do it would be to use a loop, count the length of an array, and loop through using a % mathmatical operator.
It gives you a remainder of a division: http://au2.php.net/operators.arithmetic

Related

Filter 2d array to keep all rows which contain a specific value

I have a two dimensional haystack array like this:
[
4 => [0, 1, 2, 3, 10],
1 => [0, 1, 2, 3, 10],
2 => [0, 1, 2, 3],
3 => [0, 1, 2, 3]
]
Let's say that I have a search value of $x = 10.
How can I search in above array and get an array index which contains $x.
In my current example, subarrays with key 4 and 1 contain value of $x -- I need those 2 subarrays.
You could loop then use array_search()
$array = array(...); // Your array
$x = 10;
foreach ($array as $key => $value) {
if (array_search($x, $value)) {
echo 'Found on Index ' . $key . '</br>';
}
}
Or if you need the arrays with those index
$array = array(...); // Your array
$x = 10;
$result = array(); // initialize results
foreach ($array as $key => $value) {
if (array_search($x, $value)) {
$result[] = $array[$key]; // push to result if found
}
}
print_r($result);
You can use array_filter() to keep only the array that contains the value you want:
$array = array(
array(0, 1, 2, 3, 10),
array(0, 1, 2, 3, 10),
array(0, 1, 2, 3),
array(0, 1, 2, 3)
);
$x = 10;
$out = array_filter($array, function($arr) use($x) {
return in_array($x, $arr);
});
print_r($out);
Output:
Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 10
)
[1] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 10
)
)
You can use as well in_array
$array = array(); // Your array
$x = 10;
$result = array(); // initialize results
foreach ($array as $key => $value) {
if (in_array($x, $value)) {
$result[] = $array[$key]; //
}
}
print_r($result)
You can use array_search() function to search the value in array..
Link: http://php.net/manual/en/function.array-search.php
For Exp:
$x = 10; // search value
$array = array(...); // Your array
$result = array(); // Result array
foreach ($array as $key => $value)
{
if (array_search($x, $value))
{
$result[] = $array[$key]; // push the matched data into result array..
}
}
print_r($result);
You can use array_search();
doc: http://www.php.net/manual/en/function.array-search.php

Find combination of array keys with values

In order to optimize the output I recently ran into a situation where I have to get the all the combinations of array keys inside an array. I looked into several places (including StackOverflow) but could not find the solution since most are related to permutation rather than combination.
Given this input
$input = ['jack' => 11, 'moe' => 12, 'shane' => 12];
Output should be something like this (the order inside an array does not matter).
$output = [
['jack' => 11],
['jack' => 11, 'moe' => 12]
['jack' => 11, 'moe' => 12, 'shane' => 12]
['moe' => 12],
['moe' => 12, 'shane' => 12]
['shane' => 12],
['shane' => 12, 'jack' => 11]
];
I tried this but after third iteration it does not work.
function combination(array $inputs, array $temp, &$collect) {
if (!empty($temp)) {
$collect[] = $temp;
}
for ($i = 0; $i < sizeof($inputs); $i++) {
$inputCopy = $inputs;
$elem = array_splice($inputCopy, $i, 1);
if (count($inputCopy) > 0) {
$temp[array_keys($elem)[0]] = array_values($elem)[0];
combination($inputCopy, $temp, $collect);
} else {
$temp[array_keys($elem)[0]] = array_values($elem)[0];
$collect[] = $temp;
$temp = [];
}
$i++;
}
}
Though I need this in PHP even Python (without using itertools combination), Java, Javascript will work for me.
I have found a way of doing what you want, but definitely, this is not a "fancy" solution. I would suggest you to work a little bit with it to find something better, but at least this gives you the result.
Here you go :
<?php
$baseArray = [
"joe" => 11,
"molly" => 12,
"sam" => 13,
];
function getAllPermutations($array = []) {
if (empty($array)) {
return [];
}
$result = [];
foreach ($array as $key => $value) {
unset($array[$key]);
$subPermutations = getAllPermutations($array);
$result[] = [$key => $value];
foreach ($subPermutations as $sub) {
$result[] = array_merge([$key => $value] , $sub);
}
}
return $result;
}
print_r(getAllPermutations($baseArray));
Output being :
Array
(
[0] => Array
(
[joe] => 11
)
[1] => Array
(
[joe] => 11
[molly] => 12
)
[2] => Array
(
[joe] => 11
[molly] => 12
[sam] => 13
)
[3] => Array
(
[joe] => 11
[sam] => 13
)
[4] => Array
(
[molly] => 12
)
[5] => Array
(
[molly] => 12
[sam] => 13
)
[6] => Array
(
[sam] => 13
)
) }
Hope this helped.
You read about really clever non-recursive algorithm here: PHP: Find every combination of an Array. You can adopt it (mostly copy and paste) to write generator function:
function keyCombinations($array)
{
$keys = array_keys($array);
$num = count($keys);
$total = pow(2, $num);
for ($i = 1; $i < $total; $i++) {
$combination = [];
for ($j = 0; $j < $num; $j++) {
if (pow(2, $j) & $i) {
$key = $keys[$j];
$combination[$key] = $array[$key];
}
}
yield $combination;
}
}
One important point here. In the original article $i initialized with 0, we initialize it with 1 to exclude empty array from the result.
Having this function you can get all combinations:
foreach (keyCombinations($input) as $combination) {
print_r($combination);
}
Here is working demo.
If, in your final combination, you include the empty set, your problem is equivalent to enumerating a binary number of "n" bits. Where "n" is the number of elements in your set.
You need a recursive algorithm like this one:
def comb(initialSet, results=[], currentIndex=0, currentResult=[]):
if currentIndex >= len(initialSet):
results.append( currentResult[:] )
else:
currentResult.append( initialSet[currentIndex] )
comb(initialSet, results, currentIndex + 1, currentResult)
currentResult.pop()
comb(initialSet, results, currentIndex + 1, currentResult)
return results

How to check if an array contains another array in PHP?

I would have a rather simple question today. We have the following resource:
$a = array(1 => 5, 2 => 3, 3 => 13, 9 => array('test'), 4 => 32, 5 => 33);
How is it actually possible to find out if array "a" has an array element in it and return the key if there is one (or more)?
One possible approach:
function look_for_array(array $test_var) {
foreach ($test_var as $key => $el) {
if (is_array($el)) {
return $key;
}
}
return null;
}
It's rather trivial to convert this function into collecting all such keys:
function look_for_all_arrays(array $test_var) {
$keys = [];
foreach ($test_var as $key => $el) {
if (is_array($el)) {
$keys[] = $key;
}
}
return $keys;
}
Demo.
$array = array(1 => 5, 2 => 3, 3 => 13, 9 => array('test'), 4 => 32, 5 => 33);
foreach($array as $key => $value){
if(is_Array($value)){
echo $value[key($value)];
}
}
I have tried in different way.
$a = array(1 => 5, 2 => 3, 3 => 13, 9 => array('test'), 4 => 32, 5 => 33);
foreach ( $a as $aas ):
if(is_array($aas)){
foreach ($aas as $key => $value):
echo " (child array is this $key : $value)";
endforeach;
}else{
echo " Value of array a = $aas : ";
}
endforeach;
output is like :
Value of array a = 5 : Value of array a = 3 :
Value of array a = 13 : (child array is this 0 :
test) Value of array a = 32 : Value of array a = 33 :

PHP Search array recursively and return count of index?

Is there a PHP function that lets you search an array recursively and return the number of instances a certain key 'x' occurs (regardless of how deep)?
I would use array_walk_recursive(). Example:
$a = array(1,2,3,'x',array(4,5,'x',array(6,7,8,'x')));
$v = "x";
$i = 0;
array_walk_recursive($a, function($val, $key) use (&$i, $v) {
if ($val == $v) {
$i++;
}
});
echo $i;
Output:
3
You can traverse the array recursively (that is regardless of the depth) and then count the values:
$array = array(1, 2, 3, 'x', array(4, 5, 'x', array(6, 7, 8, 'x')));
$rit = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$xCount = 0;
foreach ($rit as $value) {
if ($value === 'x') {
$xCount++;
}
}
var_dump($xCount); # int(3)
A variation of this is to convert this iteration into an array again and count values:
$array = array(1, 2, 3, 'x', array(4, 5, 'x', array(6, 7, 8, 'x')));
$rit = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$allCount = array_count_values(iterator_to_array($rit, FALSE));
print_r($allCount);
Output/Result:
Array
(
[1] => 1
[2] => 1
[3] => 1
[x] => 3
[4] => 1
[5] => 1
[6] => 1
[7] => 1
[8] => 1
)
See as well:
How do I use a recursive array iterator to process a multidimensional array?
You could write a simple recursive function that does what you want. I didn't test this, but the idea would be something like:
$count = 0;
function findKey($array,&$count){
if(!empty($array)){
foreach($array as $key => $childArray){
if($key == 'keyImLookingFor'){
$count++;
}
findKey($childArray,$count);
}
}
}
$count should then contain your number of key occurrences. Again, this might need some cleanup.
$array = array(
'key1' => 'val1',
'key2' => 'val2',
'key3' => array('key1' => 'val3'));
$count = 0;
function key_count($val, $key){
global $count;
if($key == "key1"){
$count++;
}
}
array_walk_recursive($array, 'key_count');
echo $count;

PHP Sorting Multidimensional Array Sorted by Weight

I just asked this question a moment ago but I asked incorrectly so I apologize.
I'm hoping there's an easy way to do this without tons and tons of loops.
I have a matrix in the following manner:
Foo1 Foo2 Foo3 .... FooN
Jan 1 8 5 4
Feb 10 12 15 11
Mar 12 7 4 3
Apr 10 16 7 17
Assuming the following array:
$arrayMonths = array(
'jan' => array(1, 8, 5,4)
'feb' => array(10,12,15,11)
'mar' => array(12, 7, 4, 3)
'apr' => array(10,16,7,17)
);
I need to sort the above array and show it in the following manner:
array[apr][FooN] = 17
array[feb][Foo3] = 15
array[mar][Foo1] = 12
array[jan][Foo2] = 8
Essentially, I need to get the greatest sum of the above weights, one month can only have one foo and one foo can only have one month. In the above example, the result would be 52.
Thanks
See Demo : http://codepad.org/vDI2k4n6
$arrayMonths = array(
'jan' => array(1, 8, 5,4),
'feb' => array(10,12,15,11),
'mar' => array(12, 7, 4, 3),
'apr' => array(10,16,7,17),
);
$position = array("Foo1","Foo2","Foo3","FooN");
$set = array();
foreach($arrayMonths as $key => $value)
{
$max = max($value);
$pos = array_search($max, $value);
$set[$key][$position[$pos]] = $max ;
}
function cmp($a, $b)
{
foreach($a as $key => $value )
{
foreach ($b as $bKey => $bValue)
{
return $bValue - $value ;
}
}
}
uasort($set,"cmp");
var_dump($set);
Output
array
'apr' =>
array
'FooN' => int 17
'feb' =>
array
'Foo3' => int 15
'mar' =>
array
'Foo1' => int 12
'jan' =>
array
'Foo2' => int 8
$totalArr = array();
$total = 0;
foreach($arrayMonths as $month => $row)
{
$high = max($row);
$totalArr[$month]['foo'] = $high;
$total += $high;
}
echo "Total is: " . $total . "\n\n";
print_r($totalArr);
Outputs:
Total is: 52
Array
(
[jan] => Array
(
[foo] => 8
)
[feb] => Array
(
[foo] => 15
)
[mar] => Array
(
[foo] => 12
)
[apr] => Array
(
[foo] => 17
)
)
Use uasort() if you want to sort the new array.
http://php.net/manual/en/function.uasort.php
The PHP function max() is the key here:
$sum = 0;
foreach ($array as $row) {
$sum += max($row);
}
echo $sum;
Look into this way of doing it.
http://www.php.net/manual/en/function.uasort.php
Input the array and a reference to a comparison function that you write yourself.
$arr_new = array();
foreach(array_keys($arrayMonths) as $h) {
$int_max = max($arrayMonths[$h]);
foreach(array_keys($arrMonths[$h]) as $h2)
if ($arrMonths[$h][$h2] == $int_max) {
$arr_new[$h]["foo{$h2}"] = $int_max;
break;
}
}

Categories