How do you replicate an array whilst keeping the same keys? - php

Ok. I've written a simple(ish) function to take an argument and return the same argument with the danger html characters replaced with their character entities.
The function can take as an argument either a string, an array or a 2D array - 3d arrays or more are not supported.
The function is as follows:
public function html_safe($input)
{
if(is_array($input)) //array was passed
{
$escaped_array = array();
foreach($input as $in)
{
if(is_array($in)) //another array inside the initial array found
{
$inner_array = array();
foreach($in as $i)
{
$inner_array[] = htmlspecialchars($i);
}
$escaped_array[] = $inner_array;
}
else
$escaped_array[] = htmlspecialchars($in);
}
return $escaped_array;
}
else // string
return htmlspecialchars($input);
}
This function does work, but the problem is that I need to maintain the array keys of the original array.
The purpose of this function was to make it so we could literally pass a result set from a database query and get back all the values with the HTML characters made safe. Obviously therefore, the keys in the array will be the names of database fields and my function at the moment is replacing these with numeric values.
So yeah, I need to get back the same argument passed to the function with array keys still intact (if an array was passed).
Hope that makes sense, suggestions appreciated.

You can use recursion rather than nesting loads of foreaches:
function html_safe($input) {
if (is_array($input)) {
return array_map('html_safe', $input);
} else {
return htmlspecialchars($input);
}
}

Ok I think I've figured this one out myself...
my foreach loops didn't have any keys specified for example they were:
foreach($array_val as $val)
instead of:
foreach($array_val as $key => $val)
in which case I could have preserved array keys in the output arrrays.

Related

PHP array merge: is not an array?

I'm tryin to merge an array that I have when it is being created through a function
I have a function, and it returns an array.
class myarray
{
public function getAr($id)
{
// mysql query
while($dd= $database->fetch(PDO::FETCH_ASSOC))
{
$data[] = $dd; //there's values in the array when its being populated through the function of the while loop
}
return $data;
}
public function get3($id)
{
// mysl query
while($dd= $database->fetch(PDO::FETCH_ASSOC))
{
$data[] = $dd; //there's values in the array when its being populated through the function of the while loop
}
return $data;
}
}
How come I tried to merge together the array:
$get = new myarray();
while($row = $fet->fetch(PDO::FETCH_ASSOC))
{
$arrayAr = $get->getAr($id);
$array3 = $get->get3($id);
$new_array = array_merge($arrayAr ,$array3); //this gives me the error
print_r($arrayAr); //displays array
}
print_r($arrayAr); //displays nothing, why is that?
It says that its not an array?
array_merge() [function.array-merge]: Argument #1 is not an array
But I can print_r($arrayAr); and its like an array inside the while loop, but it doesn't display anything outside of it?
when I tried this...
$new_array = array_merge((array)$arrayAr ,(array)$array3);
It doesn't display an error, but it isn't merged either.
Help?
Thanks
You $arrayAr is local variable and 2nd print_r() is used beyond of scope of his variable. If you need it available wider, "declare" it before foreach, with i.e. $arrayAr = array(); (or whatever value you want - it is not important in this case, yet array() makes code clear).

Calling PHP function in itself

In the following script function clean($data) calls it within it, that I understand but how it is cleaning data in the statement $data[clean($key)] = clean($value);??? Any help is appreciated.. I am trying to figure it out as I am new to PHP. Regards.
if (ini_get('magic_quotes_gpc')) {
function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
$data[clean($key)] = clean($value);
}
} else {
$data = stripslashes($data);
}
return $data;
}
$_GET = clean($_GET);
$_POST = clean($_POST);
$_REQUEST = clean($_REQUEST);
$_COOKIE = clean($_COOKIE);
}
Your Question:
So if I undertsand correctly you want to know what is the function doing in the line
$data[clean($key)] = clean($value);
The Answer:
See the prime purpose of the function is to remove slashes from string with php's stripslashes method.
If the input item is an array then it tries to clean the keys of the array as well as the values of the array by calling itself on the key and value.
In php arrays are like hashmaps and you can iterate over the key and value both with foreach loop like following
foreach ($data as $key => $value) {....}
So if you want to summarize the algorithm in your code snippet it would be as under
Check if the input is array. If it is not then go to step 4
For each item of array clean the key and value by calling clean method on it (Recursively)
Return the array
clean the input string using stripslashes method
5 return the cleaned input
From my understanding it's not cleaning the key but creates a new element with a clean key while the uncleaned key remains.
$a['foo\bar'] : val\ue
becomes
$a['foo\bar'] : val\ue
$a['foobar'] : value
Someone correct me if im wrong.
Maybe you'll understand the code better if it's put this way:
foreach ($data as $key => $value) {
$key = clean($key); // Clean the key, the
$value = clean($value); // Clean the value
$data[$key] = $value; // Put it in the array that will be returned
}
Assuming you have an array like this:
$_POST = array(0 => 'foo', 1 => array('bar' => 'baz'));
the following will happen:
Call clean($_POST);
call clean 0
call clean 'foo'
$return[0] = 'foo'
call clean 1
call clean 'bar'
call clean 'baz'
$return[1] = array('bar' => 'baz');
You should probably read this: http://www.codewalkers.com/c/a/Miscellaneous/Recursion-in-PHP/
The main purpose of the function is to clean an associative array or a single variable. An associative array is an array where you define keys and values for that keys; so are special arrays used in PHP like $_GET $_POST and so on.
The meaning of "cleaning" is to check whether magic quotes are active - this causes some characters in these arrays to be escaped with backslashes when you post dynamic data to a PHP page.
$_GET["Scarlett"] = "O' Hara" becomes with magic quotes $_GET["Scarlett"] = "O\' Hara"
So if magic quotes are active, the function takes care of this, and slashes are stripped so that the strings retain their correct, not escaped value.
The algorithm checks if the data passed to the function is an array, if not it cleans directly the value.
$string = "Escapes\'in\'a string";
clean($string);
is it an array? No. Then return stripslashes(my data)
$array = array("key\'with\'escapes"=>"value\'with\'escapes", "another\'key"=>"another value");
clean($array)
is it an array? Yes. So cycle through each key/value pair with foreach, take the key and clean it like the first example; then take the value and do the same and put the cleaned versions in the array.
As you see the function has two different behaviours differentiated by that "if" statement.
If you pass an array, you activate the second behaviour that in turns passes couples of strings, not arrays, triggering the first behaviour.
My thought is that this function doesn't work properly, though. Anyone got the same sensation? I have it not tested yet but it seems it's not "cleaning" the key/values in the sense of replacing them, but adds the cleaned versions along the uncleaned ones.

Split a string to form multidimensional array keys?

I'm creating JSON encoded data from PHP arrays that can be two or three levels deep, that look something like this:
[grandParent] => Array (
[parent] => Array (
[child] => myValue
)
)
The method I have, which is simply to create the nested array manually in the code requires me to use my 'setOption' function (which handles the encoding later) by typing out some horrible nested arrays, however:
$option = setOption("grandParent",array("parent"=>array("child"=>"myValue")));
I wanted to be able to get the same result by using similar notation to javascript in this instance, because I'm going to be setting many options in many pages and the above just isn't very readable, especially when the nested arrays contain multiple keys - whereas being able to do this would make much more sense:
$option = setOption("grandParent.parent.child","myValue");
Can anyone suggest a way to be able to create the multidimensional array by splitting the string on the '.' so that I can json_encode() it into a nested object?
(the setOption function purpose is to collect all of the options together into one large, nested PHP array before encoding them all in one go later, so that's where the solution would go)
EDIT: I realise I could do this in the code:
$options['grandparent']['parent']['child'] = "myValue1";
$options['grandparent']['parent']['child2'] = "myValue2";
$options['grandparent']['parent']['child3'] = "myValue3";
Which may be simpler; but a suggestion would still rock (as i'm using it as part of a wider object, so its $obj->setOption(key,value);
This ought to populate the sub-arrays for you if they haven't already been created and set keys accordingly (codepad here):
function set_opt(&$array_ptr, $key, $value) {
$keys = explode('.', $key);
// extract the last key
$last_key = array_pop($keys);
// walk/build the array to the specified key
while ($arr_key = array_shift($keys)) {
if (!array_key_exists($arr_key, $array_ptr)) {
$array_ptr[$arr_key] = array();
}
$array_ptr = &$array_ptr[$arr_key];
}
// set the final key
$array_ptr[$last_key] = $value;
}
Call it like so:
$opt_array = array();
$key = 'grandParent.parent.child';
set_opt($opt_array, $key, 'foobar');
print_r($opt_array);
In keeping with your edits, you'll probably want to adapt this to use an array within your class...but hopefully this provides a place to start!
What about $option = setOption("grandParent", { parent:{ child:"myValue" } });?
Doing $options['grandparent']['parent']['child'] will produce an error if $options['grandparent']['parent'] was not set before.
The OO version of the accepted answer (http://codepad.org/t7KdNMwV)
$object = new myClass();
$object->setOption("mySetting.mySettingsChild.mySettingsGrandChild","foobar");
echo "<pre>".print_r($object->options,true)."</pre>";
class myClass {
function __construct() {
$this->setOption("grandparent.parent.child","someDefault");
}
function _setOption(&$array_ptr, $key, $value) {
$keys = explode('.', $key);
$last_key = array_pop($keys);
while ($arr_key = array_shift($keys)) {
if (!array_key_exists($arr_key, $array_ptr)) {
$array_ptr[$arr_key] = array();
}
$array_ptr = &$array_ptr[$arr_key];
}
$array_ptr[$last_key] = $value;
}
function setOption($key,$value) {
if (!isset($this->options)) {
$this->options = array();
}
$this->_setOption($this->options, $key, $value);
return true;
}
}
#rjz solution helped me out, tho i needed to create a array from set of keys stored in array but when it came to numerical indexes, it didnt work. For those who need to create a nested array from set of array indexes stores in array as here:
$keys = array(
'variable_data',
'0',
'var_type'
);
You'll find the solution here: Php array from set of keys

detecting infinite array recursion in PHP?

i've just reworked my recursion detection algorithm in my pet project dump_r()
https://github.com/leeoniya/dump_r.php
detecting object recursion is not too difficult - you use spl_object_hash() to get the unique internal id of the object instance, store it in a dict and compare against it while dumping other nodes.
for array recursion detection, i'm a bit puzzled, i have not found anything helpful. php itself is able to identify recursion, though it seems to do it one cycle too late. EDIT: nvm, it occurs where it needs to :)
$arr = array();
$arr[] = array(&$arr);
print_r($arr);
does it have to resort to keeping track of everything in the recursion stack and do shallow comparisons against every other array element?
any help would be appreciated,
thanks!
Because of PHP's call-by-value mechanism, the only solution I see here is to iterate the array by reference, and set an arbitrary value in it, which you later check if it exists to find out if you were there before:
function iterate_array(&$arr){
if(!is_array($arr)){
print $arr;
return;
}
// if this key is present, it means you already walked this array
if(isset($arr['__been_here'])){
print 'RECURSION';
return;
}
$arr['__been_here'] = true;
foreach($arr as $key => &$value){
// print your values here, or do your stuff
if($key !== '__been_here'){
if(is_array($value)){
iterate_array($value);
}
print $value;
}
}
// you need to unset it when done because you're working with a reference...
unset($arr['__been_here']);
}
You could wrap this function into another function that accepts values instead of references, but then you would get the RECURSION notice from the 2nd level on. I think print_r does the same too.
Someone will correct me if I am wrong, but PHP is actually detecting recursion at the right moment. Your assignation simply creates the additional cycle. The example should be:
$arr = array();
$arr = array(&$arr);
Which will result in
array(1) { [0]=> &array(1) { [0]=> *RECURSION* } }
As expected.
Well, I got a bit curious myself how to detect recursion and I started to Google. I found this article http://noteslog.com/post/detecting-recursive-dependencies-in-php-composite-values/ and this solution:
function hasRecursiveDependency($value)
{
//if PHP detects recursion in a $value, then a printed $value
//will contain at least one match for the pattern /\*RECURSION\*/
$printed = print_r($value, true);
$recursionMetaUser = preg_match_all('#\*RECURSION\*#', $printed, $matches);
if ($recursionMetaUser == 0)
{
return false;
}
//if PHP detects recursion in a $value, then a serialized $value
//will contain matches for the pattern /\*RECURSION\*/ never because
//of metadata of the serialized $value, but only because of user data
$serialized = serialize($value);
$recursionUser = preg_match_all('#\*RECURSION\*#', $serialized, $matches);
//all the matches that are user data instead of metadata of the
//printed $value must be ignored
$result = $recursionMetaUser > $recursionUser;
return $result;
}

Use string to store statement (or part of a statement), and then add it to the code

I use multidimensional arrays to store product attributes (well Virtuemart does, to be precise).
When I tried to echo the sub-arrays value, if the sub-array did not exist PHP threw:
Fatal error: Cannot use string offset
as an array
To get around this, I attempted to create a function to check on every array level if it is an actual array, and if it is empty (when trying on the whole thing at once such as: is_array($array['level1']['level2']['level3']), I got the same error if level1 or level2 are not actual arrays).
This is the function ($array contains the array to check, $array_levels is an array containing the names of the sub-arrays, in the order they should apper):
function check_md_array($array,$array_levels){
if(is_array($array)){
$dimension = null; //This will store the dimensions string
foreach($array_levels as $level){
$dimension .= "['" . $level . "']"; //Add the current dimension to the dimensions string
if(!is_array($array/* THE CONTENT OF $dimension SHOULD BE INSERTED HERE*/)){
return false;
}
}
return true;
}
}
How can I take the string contained in $dimensions, and insert it into the code, to be part of the statement?
Short of doing an eval, I don't think you can do it.
if(eval("!is_array($array".$dimension.")"))
return false
However, this is another way to do it
function check_md_array($array,$array_levels){
if(!is_array($array))
return false;
foreach($array_levels as $level){
if(!isset($array[$level]) || !is_array($array[$level]))
return false;
$array = $array[$level];
}
return true;
}

Categories