note 12205 deleted from function.print-r by philip

From: Date: Tue, 04 Dec 2001 02:24:09 +0000
Subject: note 12205 deleted from function.print-r by philip
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-21586@lists.php.net to get a copy of this message
I'm very thankful to the man from the previous post. Using his code I made this function which for me is very good. First parameter $name have to be name of the variable, second arg is the variable, ther third argument must be 0. The function returns PHP code for defining the variable $name. You may wonder why you may use this function. The reason is in script(s) where you have a variable(possibly array) which you modify at runtime but want to save changes. At first sight you may serialize() the variable write it into the (included) PHP file and there must be a code which loads the deserialize()d string into variable. This approach to the problem is good but...it is hard to make changes by hand into the serialized string. Other choice is to use var_dump() or print_r and before calling one of them we start output buffering and after the call we get the content of the buffer and clear it. Now we got the content and have to parse it with preg_*() functions. As written above this a little bit of hack. This function [print_rrr()] doesn't exploit the PHP. The code seems very strange for begginers but I tried hard to keep it smaller so there are some constructions of this type (expression)? if_true:if_false. I find them very useful and use them at many places in my scripts. I wish this function will be useful for you. function print_rrr($name,$element,$level){ if(is_array($element)) { $res=str_repeat("\t",$level).($level? "\t\"".$name.'" => ':'$'.$name.' = ').'array('; $counter=1; reset($element); while(list($key,$val)=each($element)){ $res.="\n".print_rrr($key,$val,$level+1); $res.=($counter==count($element)? '':','); $counter++; } $res.="\n".str_repeat("\t",$level).($level? "\t)":');'); } else $res=str_repeat("\t",$level+1).(is_numeric($name)? $name:'"'.$name.'"').' => '.(is_numeric($element)? $element:'"'.$element.'"'); return $res; } Enjoy and have phun PHPing.

« previous php.notes (#21586) next »