hi all,

i am new to php, i have a database field called results in that i am inserting a string something like this "category_name:-abs43;c1-abs43;types:-abs43;t1"


now i want to put this string into an array, i have used the delimiter '-abs40;' as u can see in the string.

the array should be like this Array([category_name:]=>c1[types:]=>t1)

how can i accomplish this

try:

function toArray($str, $delimiter=',', $assoc=false)
{
	$data=explode($delimiter,$str);
	if(TRUE===$assoc)
	{
		$temp=array();
		$i=-1;
		$limit=count($data);
		while(++$i < $limit)
		{
			$key=$data[$i];
			$val=$data[++$i];
			$temp[ $key ]=$val;
		}
		unset($data);
		$data=$temp;
	}
return $data;
}

$str="category_name:-abs43;c1-abs43;types:-abs43;t1";
$result=toArray($str,'-abs43;',TRUE);
print_r($result);
<?php
/**
 * Explodes the supplied string by the supplied delimiter
 * and reassembles based on each even key getting the next odd value
 *
 * @param String $string
 * @param String $delimiter
 * @return Array
 */ 
function toArray($string, $delimiter){
	$pieces = explode($delimiter, $string);
	$temp = array();
	foreach($pieces as $k => $v){
		if( ($k&1) == 0 ){
			$temp[$v] = (isset($pieces[$k+1]) ? $pieces[$k+1] : '');
		}
	}
	return $temp;
}

print_r(toArray($string,'-abs43;'));
//Array ( [category_name:] => c1 [types:] => t1 )

At 100 iterations the difference is in the ten thousandths of a second.
At 10000 iterations its about 30% faster.

If you know for sure your array will ALWAYS have an even amount of value, removing the isset check and the ternary operator ( ?: ) will make it just over 50% faster.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.