PHP Function Array values not changing - php

Ive created a function that takes an array as a parameter and changes all values to 4, but it doesn't work and i don't understand why. Really bothering me, could use help thank you!
$cup3 = array (1,4,3,5,7,2);
roll($cup3);
print_r($cup3);
function roll($array)
{
foreach($array as &$value)
{
$value = 4;
}
return $array;
}
Output: (1,4,3,5,7,2) instead of all 4s

Either pass by reference &$array to edit $cup3 directly:
roll($cup3);
print_r($cup3);
function roll(&$array)
{
foreach($array as &$value)
{
$value = 4;
}
}
Or use the return from the function:
$cup3 = roll($cup3);
print_r($cup3);
function roll($array)
{
foreach($array as &$value)
{
$value = 4;
}
return $array;
}

Related

stripslashes in Multi-Dimensional array [duplicate]

I need to stripslashes all items of an array at once.
Any idea how can I do this?
foreach ($your_array as $key=>$value) {
$your_array[$key] = stripslashes($value);
}
or for many levels array use this :
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
print_r($array);
For uni-dimensional arrays, array_map will do:
$a = array_map('stripslashes', $a);
For multi-dimensional arrays you can do something like:
$a = json_decode(stripslashes(json_encode($a)), true);
This last one can be used to fix magic_quotes, see this comment.
You can use array_map:
$output = array_map('stripslashes', $array);
I found this class / function
<?php
/**
* Remove slashes from strings, arrays and objects
*
* #param mixed input data
* #return mixed cleaned input data
*/
function stripslashesFull($input)
{
if (is_array($input)) {
$input = array_map('stripslashesFull', $input);
} elseif (is_object($input)) {
$vars = get_object_vars($input);
foreach ($vars as $k=>$v) {
$input->{$k} = stripslashesFull($v);
}
} else {
$input = stripslashes($input);
}
return $input;
}
?>
on this blog and it really helped me, and now i could pass variables, arrays and objects all through the same function...
Parse array recursevely, with this solution you don't have to dublicate your array
function addslashes_extended(&$arr_r){
if(is_array($arr_r))
{
foreach ($arr_r as &$val){
is_array($val) ? addslashes_extended($val):$val=addslashes($val);
}
unset($val);
}
else
$arr_r=addslashes($arr_r);
return $arr_r;
}
Any recursive function for array :
$result= Recursiver_of_Array($array, 'stripslashes');
code:
function Recursiver_of_Array($array,$function_name=false){
//on first run, we define the desired function name to be executed on values
if ($function_name) { $GLOBALS['current_func_name']= $function_name; } else {$function_name=$GLOBALS['current_func_name'];}
//now, if it's array, then recurse, otherwise execute function
return is_array($array) ? array_map('Recursiver_of_Array', $array) : $function_name($array);
}

Find Item by key without using eval

I know that eval() is a horrible thing to use, but I couldn't think of a better way to do this.
I have the following method which I want to use to delete items from a multidimensional array, and it should delete the item if it exists.
public function delete(){
$keys = func_get_args();
$str = "";
foreach($keys as $key){
$str .= "['$key']";
}
eval("if(isset(\$_SESSION$str)){unset(\$_SESSION$str);}");
}
To use it I would make a call like so:
$obj->delete("one", "two", "three");
which would be the equivalent to this:
if(isset($_SESSION["one"]["two"]["three"])){
unset($_SESSION["one"]["two"]["three"]);
}
Is there a better way to do this than using eval()?
There is a function like that in Ouzo Goodies:
Arrays::removeNestedKey($_SESSION, ['one', 'two', 'three']);
If you don't want to include the lib, you can take a look at the source code and grab the function itself:
public static function removeNestedKey(array &$array, array $keys)
{
$key = array_shift($keys);
if (count($keys) == 0) {
unset($array[$key]);
} else {
self::removeNestedKey($array[$key], $keys);
}
}
This will achieve what you want:
function delete(){
$keys = func_get_args();
$ref = &$_SESSION;
for($x = 0; $x < sizeOf($keys)-1; $x++) {
$ref = &$ref[$keys[$x]];
}
unset($ref[$keys[sizeOf($keys)-1]]);
unset($ref);
}

Merge and sum two associatve arrays in PHP

Given these two arrays:
$first=array(
'books'=>1,
'videos'=>5,
'tapes'=>7,
);
$second=array(
'books'=>3,
'videos'=>2,
'radios'=>4,
'rc cars'=>3,
);
I would like to combine them so that I end up with
$third=array(
'books'=>4,
'videos'=>7,
'tapes'=>7,
'radios'=>4,
'rc cars'=>3,
);
I saw a function here: How to sum values of the array of the same key? but it looses the Key.
You can use something along the lines of:
function sum_associatve($arrays){
$sum = array();
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
if (isset($sum[$key])) {
$sum[$key] += $value;
} else {
$sum[$key] = $value;
}
}
}
return $sum;
}
$third=sum_associatve(array($first,$second));
Just to be different... Uses func_get_args(), closures and enforces arguments to be arrays:
function sum_associative()
{
$data = array();
array_walk($args = func_get_args(), function (array $arg) use (&$data) {
array_walk($arg, function ($value, $key) use (&$data) {
if (isset($data[$key])) {
$data[$key] += $value;
} else {
$data[$key] = $value;
}
});
});
return $data;
}

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

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