Zend - The PHP Company




Arrays

Add Code


array to string for eval()  

Type: code fragment
Added by: jbarrett
Entered: 05/09/2001
Last modified: 09/12/2000
Rating: - (fewer than 3 votes)
Views: 5589
This is a recursive function group that takes an array name and a valuename for that array and turns it into string that can be handed to eval()


<?php
/* THIS WRAPS ARRAYTOSTRINGRECURSIVE, THIS WAY MORE START VALUES CAN BE ADDED WITHOUT CHANGING THE CALLS TO THE FUNCTION */
function arraytostring($var$varname){
  if(!
is_array($var) || strlen($varname) < 1):
    return 
false;
  endif;
  
  return 
arraytostringrecursive($var$varnametruefalse);
}

function 
arraytostringrecursive($var$varname$firsttime$lasttime){
  
/* ONLY THE FIRST TIME THROUGH GETS THE  $ FOR THE NAME */
  
if($firsttime):
    
$string "$".$varname." = array (";
  else:
    
$string $varname." => array (";
  endif;
  
  
/* WATCH THE DEPTH SO A "," CAN BE PLACED AT THE CORRECT POINTS */
  
$depth sizeof($var);
  
  
/* GO THROUGH EACH ASPECT OF THE ARRAY */
  
foreach($var as $dim => $value){
    
/* BRING THE DEPTH DOWN ONE, WHEN IT IS NOT ZERO IT GETS A COMMA */
    
$depth--;
    
    
/* IF THE VALUE IS AN ARRAY RECURSE */
    
if(is_array($value)):
      
/* IF THIS IS THE LAST ELEMENT IN THE ARRAY DO NOT PLACE A COMMA ON THE END */
      
if($depth == 0):
        
$lasttime true;
      endif;
      
$string .= arraytostringrecursive($value$dimfalse$lasttime);
    else:
      
$string .= """.$dim."" => ";
      if(
is_numeric($value)):
        
$string .= $value;
      else:
        
$string .= "'".$value."'";
      endif;
      
      if(
$depth 0):
        
$string .= ", ";
      endif;
    endif;
  }

?>


Usage Example


$test[1] = 2;
$test[2][0]= 'apples';
$test[2][1] = 'jessy';
$test[smith] = 'enditall';

$string = arraytostring($test, "test");

eval($string)


Rate This Script





Search



This Category All Categories