why I cannot unset the value of an array(PHP) - php

I want to unset a field of a two-dimensional array. I got a function like this, but it doesn't work:
function excludeOldScreeningDate($array){
foreach($array as $val){
if($val['ref'] == 'G'){
unset($val['screening_date']);
}
}
return $array;
}

Because you're unsetting only temporary variable $val
function excludeOldScreeningDate($array){
foreach($array as $index => $val){
if($val['ref'] == 'G'){
unset($array[$index]['screening_date']);
}
}
return $array;

You should pass elements of an array by reference:
function excludeOldScreeningDate($array){
foreach($array as &$val){
if($val['ref'] == 'G'){
unset($val['screening_date']);
}
}
return $array;
}
Notice the foreach($array as &$val){ line has changed.

If you want to edit the values in the array, you can read each array element by reference. Put a & in front of $val in the foreach.
function excludeOldScreeningDate($array){
foreach($array as &$val){
if($val['ref'] == 'G'){
unset($val['screening_date']);
}
}
return $array;
}

Related

Updating any value in multi-dimensional arrays

I'm trying to update values in a multi-dimensional array (using a function so it can be done dynamically), but my approach of looping through each values doesn't seem to work. I tried different solutions offered on stackoverflow but I still can't seem to make it work as a function (with dynamic keys). Here is a simple example with a 2 level array, but it should work on any level.
function updateArrayValue($array,$key_to_find,$new_value){
foreach($array as $key => $value){
if($key == $key_to_find){
$value = $new_value;
break; // Stop the loop
}
}
return $array;
}
$array = array("001"=>"red", "002"=>"green", "003"=>array("003-001"=>"blue", "003-002"=>"yellow"));
$array = updateArrayValue($array,"003-001","purple");
var_dump($array);
You need recursion call of function and set new values. Not value only but changed deep array.
function updateArrayValue($array,$key_to_find,$new_value){
foreach($array as $key => $value){
// if value is not an array then try set new value if is search key
if(!is_array($value)){
if($key == $key_to_find) {
$array[$key] = $new_value;
}
}
else {
// otherwise call function again on value array
$array[$key] = updateArrayValue($value, $key_to_find, $new_value);
}
}
return $array;
}
$array = array(
"001"=> "red",
"002"=> "green",
"003"=> array(
"003-001"=> "blue",
"003-002"=> "yellow"
));
$newArray = updateArrayValue($array,"003-001","purple");
var_dump($newArray);

PHP Array Search with key values

I have following arrays :
<?php
$a=array(
"abc"=>array("red","white","orange"),
"def"=>array("green","vilot","yellow"),
"xyz"=>array("blue","dark","pure")
);
echo array_search(array("dark"),$a);
?>
How to get output of xyz in array list.
array_search returns false or the key. Since you have multiple dimensions you must loop through to get the lowest level.
Since we are in another dimension your return will actually be 1. For this reason, if array_search succeeds we must use the key that is defined in the foreach
<?php
$a=array("abc"=>array("red","white","orange"),"def"=>array("green","vilot","yellow"),"xyz"=>array("blue","dark","pure"));
foreach($a as $key=>$data){
if(array_search("dark",$data)){
echo $key;
}
}
Outputs: xyz
You can create one user-define function to check value
$a=array("abc"=>array("red","white","orange"),"def"=>array("green","vilot","yellow"),"xyz"=>array("blue","dark","pure"));
function search_data($value, $array) {
foreach ($array as $key => $val) {
if(is_array($val) && in_array($value,$val))
{
return $key;
}
}
return null;
}
echo search_data("dark",$a);
DEMO
Please try this
function searchMultiArray($arrayVal,$val){
foreach($arrayVal as $key => $suba){
if (in_array($val, $suba)) {
return $key;
}
}
}
$a = array("abc"=>array("red","white","orange"),"def"=>array("green","vilot","yellow"),"xyz"=>array("blue","dark","pure"));
echo $keyVal = searchMultiArray($a , "dark");

getting variables from an array where some variables are arrays

I am struggling of getting values extracted from an array where some values are values and some values are arrays.
global $globals;
foreach($globals as $value)
{
if ($value == "array")
{
global $$value = array;
}
else
{
global $$value;
}
}
Everything is fine except this part: global $$value = array; How to foreach $value as array?
Perhaps you could make use of the PHP is_array function ?
http://php.net/manual/en/function.is-array.php
e.g.
if(is_array($value)) {
echo 'Is Array';
} else {
echo 'not an Array';
}
I think what you're trying to accomplish is to check if any $value in the $globals is array or not, for that you may use is_array and use for each as per your needs.
foreach($globals as $value)
{
if (is_array($value)){
foreach ($value as $new_value) {
# Your job
}
}
//
//other codes
}

Unset inside array_walk_recursive not working

array_walk_recursive($arr, function(&$val, $key){
if($val == 'smth'){
unset($val); // <- not working, unset($key) doesn't either
$var = null; // <- setting it to null works
}
});
print_r($arr);
I don't want it to be null, I want the element out of the array completely. Is this even possible with array_walk_recursive?
You can't use array_walk_recursive here but you can write your own function. It's easy:
function array_unset_recursive(&$array, $remove) {
$remove = (array)$remove;
foreach ($array as $key => &$value) {
if (in_array($value, $remove)) {
unset($array[$key]);
} elseif (is_array($value)) {
array_unset_recursive($value, $remove);
}
}
}
And usage:
array_unset_recursive($arr, 'smth');
or remove several values:
array_unset_recursive($arr, ['smth', 51]);
unset($val) will only remove the local $val variable.
There is no (sane) way how you can remove an element from the array inside array_walk_recursive. You probably will have to write a custom recursive function to do so.
The answer of #dfsq is correct but this function doesn't remove empty array. So you can end up with Tree of empty array, which is not what is expected in most cases.
I used this modified function instead:
public function array_unset_recursive(&$array, $remove) {
foreach ($array as $key => &$value) {
if (is_array($value)) {
$arraySize = $this->array_unset_recursive($value, $remove);
if (!$arraySize) {
unset($array[$key]);
}
} else if (in_array($key, $remove, true)){
unset($array[$key]);
}
}
return count($array);
}

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