php foreach on array when arrays might be nested - php

The following code uses foreach on an array and if the value is an array it does a for each on the nested array
foreach ($playfull as $a)
{
if (is_array($a))
{
foreach ($a as $b)
{
print($b);
print("<p>");
}
} else {
print($a);
print("<p>");
}
}
This only works if you know that the arrays may only be nested one level deep
If arrays could be nested an unknown number of levels deep how do you achieve the same result? (The desired result being to print the value of every key in every array no matter how deeply nested they are)

You can use array_walk_recursive. Example:
array_walk_recursive($array, function (&$val)
{
print($val);
}
This function is a PHP built in function and it is short.

Use recursive functions (that are functions calling themselves):
function print_array_recursively($a)
{
foreach ($a as $el)
{
if (is_array($el))
{
print_array_recursively($el);
}
else
{
print($el);
}
}
}
This is the way, print_r could do it (see comments).

You want to use recursion, you want to call your printing function in itself, whenever you find an array, click here to see an example
$myArray = array(
"foo",
"bar",
"children" => array(
"biz",
"baz"),
"grandchildren" => array(
"bang" => array(
"pow",
"wow")));
function print_array($playfull)
{
foreach ($playfull as $a)
{
if (is_array($a))
{
print_array($a);
} else {
echo $a;
echo "<p>";
}
}
}
echo "Print Array\n";
print_array($myArray);

You could use a recursive function, but the max depth will be determined by the maximum nesting limit (see this SO question, Increasing nesting functions calls limit, for details about increasing that if you need it)
Here's an example:
$array = array(1,array(2,3,array(4,5)),6,7,8);
function printArray($item)
{
foreach ($item as $a)
{
if (is_array($a))
{
printArray($a);
} else {
print($a);
print("<p>");
}
}
}
printArray($array);
I hope that helps.

Try this -
function array_iterate($arr, $level=0, $maxLevel=0)
{
if (is_array($arr))
{
// unnecessary for this conditional to enclose
// the foreach loop
if ($maxLevel < ++$level)
{ $maxLevel = $level; }
foreach($arr AS $k => $v)
{
// for this to work, the result must be stored
// back into $maxLevel
// FOR TESTING ONLY:
echo("<br>|k=$k|v=$v|level=$level|maxLevel=$maxLevel|");
$maxLevel= array_iterate($v, $level, $maxLevel);
}
$level--;
}
// the conditional that was here caused all kinds
// of problems. so i got rid of it
return($maxLevel);
}
$array[] = 'hi';
$array[] = 'there';
$array[] = 'how';
$array['blobone'][] = 'how';
$array['blobone'][] = 'are';
$array['blobone'][] = 'you';
$array[] = 'this';
$array['this'][] = 'is';
$array['this']['is'][] = 'five';
$array['this']['is']['five'][] = 'levels';
$array['this']['is']['five']['levels'] = 'deep';
$array[] = 'the';
$array[] = 'here';
$var = array_iterate($array);
echo("<br><br><pre>$var");

Related

PHP array_filter weird behavior

I'm using array_filter with multiple parameters but it's not doing the filter correctly. Here where it's supposed to return an array with only "arts,crafts,designs" as an element, it's returning an empty array. The only $askedcat parameter it works for is "arts". I can't find out what the issue is.
I've tried not using an array_filter and instead just looping over the array, and I get the same problem.
<?php
class CategoryFilter {
public $categoryAskedFor;
function __construct($askedCat) {
$this->categoryAskedFor = $askedCat;
}
function categoryCallback($projectCategoryString) {
$project_category_array = explode(",", $projectCategoryString);
if(in_array($this->categoryAskedFor, $project_category_array)) return true;
return false;
}
}
$verifiedProjects = ["arts", "arts,crafts,designs", "film", "film,theater"];
$askedCat = "crafts";
$newArr = array_filter($verifiedProjects, array(new CategoryFilter($askedCat), "categoryCallback"));
for ($i = 0; $i < count($newArr); $i++) {
echo $newArr[$i] . "<br>";
}
I expect the output here to be arts,crafts,design<br> but it's only <br> meaning the array is empty.
There are many way to achieve this but let me show you two way here
WAY #1
If you using the for loop to retrieve the array value then need to have numeric key and as per your code you need array_values function to manage that
<?php
class CategoryFilter {
public $categoryAskedFor;
function __construct($askedCat) {
$this->categoryAskedFor = $askedCat;
}
function categoryCallback($projectCategoryString) {
$project_category_array = explode(",", $projectCategoryString);
if(in_array($this->categoryAskedFor, $project_category_array)) return true;
return false;
}
}
$verifiedProjects = ["arts", "arts,crafts,designs", "film", "film,theater"];
$askedCat = "crafts";
$newArr = array_filter($verifiedProjects, array(new CategoryFilter($askedCat), "categoryCallback"));
$newArr = array_values($newArr);
for ($i = 0; $i < count($newArr); $i++) {
echo $newArr[$i] . "<br>";
}
WAY # 2
If you don't want to use the array_values here then you need to manage the foreach loop instead of for loop
<?php
class CategoryFilter {
public $categoryAskedFor;
function __construct($askedCat) {
$this->categoryAskedFor = $askedCat;
}
function categoryCallback($projectCategoryString) {
$project_category_array = explode(",", $projectCategoryString);
if(in_array($this->categoryAskedFor, $project_category_array)) return true;
return false;
}
}
$verifiedProjects = ["arts", "arts,crafts,designs", "film", "film,theater"];
$askedCat = "crafts";
$newArr = array_filter($verifiedProjects, array(new CategoryFilter($askedCat), "categoryCallback"));
foreach ($newArr as $value) {
echo $value . "<br>";
}
The way you're looping over your resulting array is wrong, because array_filter will preserve the array keys. The 0 index may not be there in the filtered version (and in your case, it actually isn't).
Use foreach instead:
foreach ($newArr as $value) {
echo $value, '<br>';
}
array_filter will remove elements but will not reset the keys. use array_values to reset the keys first.
$newArr = array_values($newArr);
for ($i = 0; $i < count($newArr); $i++) {
echo $newArr[$i] . "<br>";
}
You will get as per your output
$askedCat = 'crafts';
$verifiedProjects = ["arts", "arts,crafts,designs", "film", "film,theater"];
$newArr = array_filter($verifiedProjects, function ($item) use ($askedCat) {
if (stripos($item, $askedCat) !== false) {
return true;
}
return false;
});
foreach ($newArr as $value) {
echo $value . "<br>";
}

how can I get my php array data to persist?

When I query the data within the foreach loop it works, but makes a duplicate for each pass in the loop. I try to var_dump it anywhere else outside the loop and the data isn't there. Why won't my data persist outside the forEach loop?
<?php
$old_array = [10-2, 13=>"3452", 4=>"Green",
5=>"Green", 6=>"Blue", "green"=>"green",
"two"=>"green" ,"2"=>"green" , "rulebreak" =>"GrEeN",
"ninja"=>" Green ", ["blue" => "green", "green"=>"green", 2 => "itsGreen"] ];
$newArray = array();
function filter_Green($array) {
$find = "green";
$replace = "not green";
/* Same result as using str_replace on an array, but does so recursively for multi-dimensional arrays */
/* found here:
if (!is_array($array)) {
/* Used ireplace so that searches can be case insensitive */
return str_ireplace($find, $replace, $array);
}
foreach ($array as $key => $value) {
$newArray[$key] = $value;
if ($key == "green") {
$newArray[$key] = "not green";
}
if ($value == "green") {
$newArray[$value] = "not green";
}
}
return $newArray;
}
filter_Green($old_array);
var_dump($newArray);
?>
Expectation: When I run the function it should replace all instances of "green" with "not green" and save those into a $newArray. I have it returning $newArray but even then it doesn't seem to match up that the values are being saved into the newArray, hence why I'm doing var_dump to check if it's even working (it appears to not be)
Results: as it is setup, I get an empty array returned to me...It seems to work somewhat if I move var_dump($newArray) to within the foreach loop but that then duplicates the data for each pass.
if you want var_dump $newArray out side the function then you should declare $newArray as global in your function
<?php
$old_array = [10-2, 13=>"3452", 4=>"Green", 5=>"Green", 6=>"Blue", "green"=>"green", "two"=>"green" ,"2"=>"green" , "rulebreak" =>"GrEeN", "ninja"=>" Green ", ["blue" => "green", "green"=>"green", 2 => "itsGreen"] ];
$newArray = array();
function filter_Green($array) {
global $newArray;
$find = "green";
$replace = "not green";
/* Same result as using str_replace on an array, but does so recursively for multi-dimensional arrays */
if (!is_array($array)) {
/* Used ireplace so that searches can be case insensitive */
return str_ireplace($find, $replace, $array);
}
foreach ($array as $key => $value) {
$newArray[$key] = $value;
if ($key == "green") {
$newArray[$key] = "not green";
}
if ($value == "green") {
$newArray[$value] = "not green";
}
}
return $newArray;
}
filter_Green($old_array);
var_dump($newArray);
?>
But instead of declaring global in function, use returned value by filter_Green($old_array); as below
$result = filter_Green($old_array);
var_dump($result);

finding an array range in PHP

I have a range of values in an array like:
$values = array(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5);
I need to find the index of the smallest value in that array that's greater than or equal to a specified number. For example, if the user inputs 0.25, I need to know that the first array index is 2.
In other languages I've used, like R, there is a 'which' function that will return an array of indices that meet some criteria. I've not found that in PHP, so i'm hopeful someone else has solved this.
Thanks.
You can use array_filter
It does exactly what R which does.
Hope this function will help you,
function find_closest_item($array, $number) {
sort($array);
foreach ($array as $a) {
if ($a >= $number) return $a;
}
return end($array); // or return NULL;
}
I don't know if there's a built in function for that, but this should work:
function getClosest($input, $array)
{
foreach($array as $value)
{
if ($value >= $input)
{
return $value;
}
}
return false;
}
You can use the following working logic. There might be other built in functions which can be used to solve this problem.
<?php
$values = array(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5);
$search=0.35;
$result_index = NULL;
$result_value=NULL;
$count=count($values);
for($i=0;$i<$count;$i++) {
if($values[$i]<$search) {
continue;
}
if($result_index==NULL) {
$result_index = $i;
$result_value = $values[$i];
continue;
}
if($values[$i]<$result_value) {
$result_index = $i;
$result_value = $values[$i];
}
}
print $result_index . " " . $result_value;
?>
You can build your own custom function:
function findIndex($input_array, $num)
{
foreach($input_array as $k => $v)
{
if($v >= $num)
{
return $k;
}
}
return false;
}
This function will return array index (key). If you don't want index, but the value, then other functions posted here will do the job. You should clarify what exactly you want to get as your question is a little bit amiguous

How to delete elements in array?

I have an array like this :
array() {
["AG12345"]=>
array() {
}
["AG12548"]=>
array() {
}
["VP123"]=>
array() {
}
I need to keep only arrays with keys which begin with "VP"
It's possible to do it with one function ?
Yes, just use unset():
foreach ($array as $key=>$value)
{
if(substr($key,0,2)!=="VP")
{
unset($array[$key]);
}
}
From a previous question: How to delete object from array inside foreach loop?
foreach($array as $elementKey => $element) {
if(strpos($elementKey, "VP") == 0){
//delete this particular object from the $array
unset($array[$elementKey]);
}
}
This works for me:
$prefix = 'VP';
for ($i=0; $i <= count($arr); $i++) {
if (strpos($arr[$i], $prefix) !== 0)
unset($arr[$i]);
}
Another alternative (this would be way simpler if it were values instead):
array_intersect_key($arr, array_flip(preg_grep('~^VP~', array_keys($arr))));
This is only a sample how to do this, you have probably many other ways!
// sample array
$alpha = array("AG12345"=>"AG12345", "VP12548"=>"VP12548");
foreach($alpha as $val)
{
$arr2 = str_split($val, 2);
if ($arr2[0] == "VP")
$new_array = array($arr2[0]=>"your_values");
}

access php array children through parameters?

I have a unique case where I have an array like so:
$a = array('a' => array('b' => array('c' => 'woohoo!')));
I want to access values of the array in a manner like this:
some_function($a, array('a')) which would return the array for position a
some_function($a, array('a', 'b', 'c')) which would return the word 'woohoo'
So basically, it drills down in the array using the passed in variables in the second param and checks for the existence of that key in the result. Any ideas on some native php functions that can help do this? I'm assuming it'll need to make use of recursion. Any thoughts would be really appreciated.
Thanks.
This is untested but you shouldn't need recursion to handle this case:
function getValueByKey($array, $key) {
foreach ($key as $val) {
if (!empty($array[$val])) {
$array = $array[$val];
} else return false;
}
return $array;
}
You could try with RecursiveArrayIterator
Here is an example on how to use it.
Here’s a recursive implementation:
function some_function($array, $path) {
if (!count($path)) {
return;
}
$key = array_shift($path);
if (!array_key_exists($key, $array)) {
return;
}
if (count($path) > 1) {
return some_function($array[$key], $path);
} else {
return $array[$key];
}
}
And an iterative implementation:
function some_function($array, $path) {
if (!count($path)) {
return;
}
$tmp = &$array;
foreach ($path as $key) {
if (!array_key_exists($key, $tmp)) {
return;
}
$tmp = &$tmp[$key];
}
return $tmp;
}
These functions will return null if the path is not valid.
$a['a'] returns the array at position a.
$a['a']['b']['c'] returns woohoo.
Won't this do?

Categories