Re: PHP: array to string?
This simple function converts a PHP array to a string containing a PHP array declaration. It can be used to put an array into a database field. It can then be retrieved and eval()'d in another script.
Code:
<?php
$arr = array('h','e','l','l','o');
$string = implode($arr, '');
?>
Re: PHP: array to string?
The function below facilitates the process of converting an array to a string. Very useful for building SQL insert queries with arrays of data.
Code:
<?php
function array2str($array, $pre = '', $pad = '', $sep = ', ')
{
$str = '';
if(is_array($array)) {
if(count($array)) {
foreach($array as $v) {
$str .= $pre.$v.$pad.$sep;
}
$str = substr($str, 0, -strlen($sep));
}
} else {
$str .= $pre.$array.$pad;
}
return $str;
}
?>
Re: PHP: array to string?
I’ve been working a great deal with vBulletin, our forums system, and in doing so have had to brush on my PHP. Through the course of preparing the system for the summer I’ve come across a few PHP functions that I was not aware. Here’s a few that you may not know about:
implode: takes an array of strings and concatenates them, using $glue as a separator.
Example: string implode (string $glue, array $pieces)
$before = array(’one’, ‘two’, ‘three’);
$after = implode(”,”, $before);
echo $after;
Produces:one,two,three
Re: PHP: array to string?
Arrays are not automatically passed by reference in PHP (unlike C, for instance). As with other variables, however, you can write your functions to accept arrays as pass-by-reference arguments. Of course, this applies only to PHP 4.
Code:
Create an array of user information with defaults, then fill it with information. */
$user_info = array('lastname' => '',
'initial' => '',
'firstname' => '',
'homedir' => '');
$user_info['lastname'] = 'User';
$user_info['initial'] = 'L.';
$user_info['firstname'] = 'Joe';
$user_info['homedir'] = '/home/joeluser';
/* Filling an indexed array with the letters of the English alphabet. */
$arr = array();
for ($i = 97; $i < 123; $i++) {
$arr[] = chr($i);
}
print_r($arr);
/* Do the same thing, but make an array containing two arrays, one of uppercase
* letters and one of lowercase. */
$arr = array();
for ($i = 97; $i < 123; $i++) {
$arr['lowercase'][] = chr($i);
$arr['uppercase'][] = chr($i - 32);
}
print_r($arr);