pyronaur
pyronaur

Reputation: 3545

Getting one value out of a serialized array in PHP

What would you say is the most efficient way to get a single value out of an Array. I know what it is, I know where it is. Currently I'm doing it with:

 $array = unserialize($storedArray);
 $var = $array['keyOne'];

Wondering if there is a better way.

Upvotes: 3

Views: 12110

Answers (6)

smat88dd
smat88dd

Reputation: 2388

I, too, think the right way is to un-serialize.

But another way could be to use string operations, when you know what you want from the array:

$storedArray = 'a:2:{s:4:"test";s:2:"ja";s:6:"keyOne";i:5;}';
# another: a:2:{s:4:"test";s:2:"ja";s:6:"keyOne";s:3:"sdf";}
$split = explode('keyOne', $storedArray, 2);
# $split[1] contains the value and junk before and after the value
$splitagain = explode(';', $split[1], 3);
# $splitagain[1] should be the value with type information
$value = array_pop(explode(':', $splitagain[1], 3));
# $value contains the value

Now, someone up for a benchmark? ;) Another way might be RegEx ?

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157839

Sure.
If you need a better way - DO NOT USE serialized arrays.
Serialization is just a transport format, of VERY limited use.

If you need some optimized variant - there are hundreds of them.
For example, you can pass some single scalar variable instead of whole array. And access it immediately

Upvotes: 0

hakre
hakre

Reputation: 197659

Wondering if there is a better way.

For the example you give with the array, I think you're fine.

If the serialized string contains data and objects you don't want to unserialize (e.g. creating objects you really don't want to have), you can use the Serialized PHP library which is a complete parser for serialized data.

It offers low-level access to serialized data statically, so you can only extract a subset of data and/or manipulate the serialized data w/o unserializing it. However that looks too much for your example as you only have an array and you don't need to filter/differ too much I guess.

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382666

You are doing it fine, I can't think of a better way than what you are doing.

  • You unserialize
  • You get an array
  • You get value by specifying index

That's the way it can be done.

Upvotes: 2

Authman Apatira
Authman Apatira

Reputation: 4054

If you dont want to unseralize the whole thing (which can be costly, especially for more complex objects), you can just do a strpos and look for the features you want and extract them

Upvotes: 0

Aurimas Ličkus
Aurimas Ličkus

Reputation: 10074

Its most efficient way you can do, unserialize and get data, if you need optimize dont store all variables serialized.

Also there is always way to parse it with regexp :)

Upvotes: 0

Related Questions