note 54601 added to ref.array

From: Date: Fri, 08 Jul 2005 20:49:14 +0000
Subject: note 54601 added to ref.array
Groups: php.notes 
Request: Send a blank email to php-notes+get-91699@lists.php.net to get a copy of this message
Several people here have posted functions for converting arrays to strings, but nobody posted a sister function that would convert it back. Also, their data is not URL safe. These functions are URL safe, hide the data by MIME encoding it, and are much shorter. Enjoy. :-) <?php // Converts an array to a string that is safe to pass via a URL function array_to_string($array) { $retval = ''; foreach ($array as $index => $value) { $retval .= urlencode(base64_encode($index)) . '|' . urlencode(base64_encode($value)) . '||'; } return urlencode(substr($retval, 0, -2)); } // Converts a string created by array_to_string() back into an array. function string_to_array($string) { $retval = array(); $string = urldecode($string); $tmp_array = explode('||', $string); foreach ($tmp_array as $tmp_val) { list($index, $value) = explode('|', $tmp_val); $retval[base64_decode(urldecode($index))] = base64_decode(urldecode($value)); } return $retval; } // Example: $array1 = array('index1' => 'val1', 'index2' => 'val2', 'index3' => 'val3'); echo '<pre>'; print_r($array1); echo '</pre>'; $string = array_to_string($array1); echo '$string: '.$string.'<br />'; $array2 = string_to_array($string); echo '<pre>'; print_r($array2); echo '</pre>'; ?> ---- Manual Page -- http://www.php.net/manual/en/ref.array.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+54601 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+54601&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+54601&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+54601&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+54601&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+54601&report=yes&reason=non-english Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+54601&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+54601&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#91699) next »