How to check if an array contains another array in PHP? - 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 :

Related

PHP: Accumulate values in associative array

I would like to accumulate values in an associative array depending on part of the key.
I have tested this foreach loop which works fine in an indexed array:
$b = array();
foreach ($a as $key => $value) {
if ($key > 0) {
$b[$key] = $b[$key - 1] + $value;
}
}
I can't get it to work in an associative array, though...
$a (excerpt)
Array (
[2014-04-22|Paul] => 0
[2014-04-28|Paul] => 2
[2014-05-13|Paul] => 0
[2014-06-03|Paul] => 1
[2014-06-12|Paul] => 0
[2014-08-11|Paul] => 1
[2014-08-28|Paul] => 3
[2012-05-09|John] => 1
[2012-08-29|John] => 2
[2012-09-05|John] => 0
[2012-09-13|John] => 1
)
$b (desired result)
Array (
[2014-04-22|Paul] => 0
[2014-04-28|Paul] => 2
[2014-05-13|Paul] => 2
[2014-06-03|Paul] => 3
[2014-06-12|Paul] => 3
[2014-08-11|Paul] => 4
[2014-08-28|Paul] => 7
[2012-05-09|John] => 1
[2012-08-29|John] => 3
[2012-09-05|John] => 3
[2012-09-13|John] => 4
)
In the desired result each value is of 'Paul' and 'John' (and more) is accumulated to the previous one.
You can do this by keeping track of the name parts of the keys, and resetting the total count when you get to a new name:
$b = array();
$lastname = '';
foreach ($a as $key => $value) {
list($d, $n) = explode('|', $key);
if ($n == $lastname) {
$total += $value;
}
else {
$total = $value;
}
$b[$key] = $total;
$lastname = $n;
}
print_r($b);
Output:
Array (
[2014-04-22|Paul] => 0
[2014-04-28|Paul] => 2
[2014-05-13|Paul] => 2
[2014-06-03|Paul] => 3
[2014-06-12|Paul] => 3
[2014-08-11|Paul] => 4
[2014-08-28|Paul] => 7
[2012-05-09|John] => 1
[2012-08-29|John] => 3
[2012-09-05|John] => 3
[2012-09-13|John] => 4
)
Demo on 3v4l.org
By using array_walk, check if current name is same as next name, as per that I am resetting value by next.
$result = [];
$tempKey = '';
$arr = array_walk($arr, function($item, $key) use(&$result, &$tempKey, &$total){
list($date, $name) = explode("|", $key); // explode key
if(empty($tempKey) || $tempKey != $name){ // if empty or if conflict
$tempKey = $name; // tempKey for reference
$total = $item; // total reset to current value
}else{
$total += $item; // adding for same name
}
$result[$key] = $total; // putting calculated value
});
print_r($result);
Output
Array
(
[2014-04-22|Paul] => 0
[2014-04-28|Paul] => 2
[2014-05-13|Paul] => 2
[2014-06-03|Paul] => 3
[2014-06-12|Paul] => 3
[2014-08-11|Paul] => 4
[2014-08-28|Paul] => 7
[2012-05-09|John] => 1
[2012-08-29|John] => 3
[2012-09-05|John] => 3
[2012-09-13|John] => 4
)
Demo.

PHP Pointers behaving unexpectedly

While working on a project which checks the if Laravel models are related to each other I noticed some (weird?) pointer behavior going on with PHP. Below is a minimal example to reproduce what I found.
<?php
$arr = ['a', 'b', ['c']];
foreach($arr as &$letter) {
if (!is_array($letter)) {
$letter = [$letter];
}
}
dump($arr);
foreach($arr as $letter) {
dump($arr);
}
function dump(...$dump) {
echo '<pre>';
var_dump($dump);
echo '</pre>';
}
At first I expected the dumps in this response to all return the same data:
[ ['a'], ['b'], ['c'] ]
But that is not what happened, I got the following responses:
[ ['a'], ['b'], ['c'] ]
[ ['a'], ['b'], ['a'] ]
[ ['a'], ['b'], ['b'] ]
[ ['a'], ['b'], ['b'] ]
A running example can be found here.
Why do the pointers act this way? How can I update $letter in the first loop without having to do $arr[$key] = $letter?
Edit: As people seem to be misunderstanding why there is a second foreach loop, this is to show that the array is changing without being reassigned
According to the PHP documentation:
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
// Without an `unset($value)`, `$value` is still a reference to the last item: `$arr[3]`
foreach ($arr as $key => $value) {
// $arr[3] will be updated with each value from $arr...
echo "{$key} => {$value} ";
print_r($arr);
}
// ...until ultimately the second-to-last value is copied onto the last value
/* output:
0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 ) */
First of all: PHP doesn't have pointers, it has references. See What references are and What references are not for more information.
The reason this happens is that $letter after the foreach loop still holds a reference to the last element of your array (which is [c]). So in your second loop, you're overriding not only $letter while looping but also the reference it points to.
To solve the problem you need to unset($letter) after your first loop:
$arr = ['a', 'b', ['c']];
foreach($arr as &$letter) {
if (!is_array($letter)) {
$letter = [$letter];
}
}
unset($letter); // this is important
dump($arr);
foreach($arr as $letter) {
dump($arr);
}
function dump(...$dump) {
echo '<pre>';
var_dump($dump);
echo '</pre>';
}

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

Merge keys of an array based on values

I want to merge the keys of array based on values. This is my array.
Array
(
[1] => 1
[2] => 1
[3] => 1
[4] => 2
[5] => 0
[6] => 2
[7] => 2
)
I want output as
Array
(
[1,2,3] => 1
[4,6,7] => 2
[5] => 0
)
I have been brain storming entire day but couldn't find a solution. Any hint would be much appreciated.
WHAT I HAVE TRIED:
for($i=2;$i<=count($new);$i++){
if ($new[$i-1][1]==$new[$i][1]){
$same .= $new[$i-1][0].$new[$i][0];
}
}
echo $same;
But I am stucked. I am comparing the keys one by one but it's very complicated. I don't need the code. I only need the hint or logic. Anyone kind enough?
<?php
$old_arr = ["1"=>1,"2"=>1,"3"=>1,"4"=>2,"5"=>0,"6"=>2,"7"=>2];
$tmp = array();
foreach($old_arr as $key=>$value)
{
if(in_array($value, $tmp)){
$index = array_search($value, $tmp);
unset($tmp[$index]);
$tmp[$index.",".$key] = $value;
}else{
$tmp[$key] = $value;
}
}
ksort($tmp);
echo "<pre>";
print_r($tmp);
echo "</pre>";
?>
https://eval.in/529314
You can loop through array elements and create a new array with new structure. Please check the below code it may help you
$old_array = array(1=> 1,2 => 1,
3=> 1,
4 => 2,
5 => 0,
6 => 2,
7 => 2
);
$new_array = array();
foreach($old_array as $key => $value)
{
if(in_array($value,$new_array))
{
$key_new = array_search($value, $new_array);//to get the key of element
unset($new_array[$key_new]); //remove the element
$key_new = $key_new.','.$key; //updating the key
$new_array[$key_new] = $value; //inserting new element to the key
}
else
{
$new_array[$key] = $value;
}
}
print_r($new_array);
$arr = array(1 => 1, 2 => 1, 3 => 1, 4 => 2, 5 => 0, 6 => 2, 7 => 2);
$tmp = array();
foreach ($arr as $key => $val)
$tmp[$val][] = $key;
$new = array();
foreach ($tmp as $key => $val)
$new[implode(',', $val)] = $key;
First loop the original array through, creating a temporary array, where your original values are keys and values are the original keys as an array.
Then loop the temporary array, creating the new array, where the temporary array's values are imploded as keys.
There's no way to have an array of keys to a single value, but the other way around:
function flipWithKeyArray($arr){
$result = array();
foreach($arr as $key => $val){
if(!isset($result[$val]))
$result[$val] = array();
$result[$val][] = $key;
}
return $result;
}
This will flip your array and declare one array per value of your old array and then push the keys with the same value into each list.
For an array like this:
array(1=>1, 2=>1, 3=>1, 4=>2, 5=>2, 6=>2)
The result will look like this:
array(1=>array(1,2,3), 2=>array(4,5,6))
Hope it fits your need.

Getting specidic values from PHP arrays

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

Categories