How to extract data from (array?) with colons [duplicate] - php

My problem is very basic.
I did not find any example to meet my needs as to what exactly serialize() and unserialize() mean in php? They just give an example - serialize an array and show an output in an unexplained format. It is really hard to understand the basic concept going through their jargon.
EDIT:
<?php
$a= array( '1' => 'elem 1', '2'=> 'elem 2', '3'=>' elem 3');
print_r($a);
echo ("<br></br>");
$b=serialize($a);
print_r($b);
?>
output:
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
I cannot understand the second output. Besides that, can anyone give an example of a situation that I need to serialize a php array before using it?

A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serialize is just a format to express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.
Take for example this common problem:
How do I pass a PHP array to Javascript?
PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript?
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:
{ 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }
Javascript can easily reverse this into an actual Javascript array.
This is just as valid a representation of the same data structure though:
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
But pretty much only PHP uses it, there's little support for this format anywhere else.
This is very common and well supported as well though:
<array>
<element key='1'>elem 1</element>
<element key='2'>elem 2</element>
<element key='3'>elem 3</element>
</array>
There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.

PHP serialize() unserialize() usage
http://freeonlinetools24.com/serialize
echo '<pre>';
// say you have an array something like this
$multidimentional_array= array(
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 4, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 5, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 8, 7)
)
);
// serialize
$serialized_array=serialize($multidimentional_array);
print_r($serialized_array);
Which gives you an output something like this
a:3:{i:0;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:4;i:2;i:7;}}i:1;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:5;i:2;i:7;}}i:2;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:8;i:2;i:7;}}}
again if you want to get the original array back just use PHP unserialize() function
$original_array=unserialize($serialized_array, ['allowed_classes' => false]);
var_export($original_array);
I hope this will help
Note: Set allowed_classes to false in unserialize for security reasons. See Warning https://www.php.net/manual/en/function.unserialize.php

<?php
$a= array("1","2","3");
print_r($a);
$b=serialize($a);
echo $b;
$c=unserialize($b, ['allowed_classes' => false]);
print_r($c);
Run this program its echo the output
a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}
Note: Set allowed_classes to false in unserialize for security reasons.
here
a=size of array
i=count of array number
s=size of array values
you can use serialize to store array of data in database and can retrieve and UN-serialize data to use. See Warning https://www.php.net/manual/en/function.unserialize.php

When you want to make your php value storable, you have to turn it to be a string value, that is what serialize() does. And unserialize() does the reverse thing.

Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.
Instead, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().
If you are familiar with json_encode() and json_decode() (and JSON in general), the concept is similar.

Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.
it makes really difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.
That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.
A good example of serialize() and unserialize() could be like this:
$posts = base64_encode(serialize($_POST));
header("Location: $_SERVER[REQUEST_URI]?x=$posts");
Unserialize on the page
if($_GET['x']) {
// unpack serialize and encoded URL
$_POST = unserialize(base64_decode($_GET['x']));
}

From http://php.net/manual/en/function.serialize.php :
Generates a storable representation of a value.
This is useful for storing or passing PHP values around without losing their type and structure.
Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).
Unserialize is used to convert the string back to an object.

Basically, when you serialize arrays or objects you simply turn it to a valid string format so that you can easily store them outside of the php script.
Use serialize to save the state of an object in database (lets take the User class as an example) Next unserialize the data to load the previous state back to the object (methods are not serializer you need to include object class to be able to use it)
user personalization
Note for object you should use magic __sleep and __wakeup methods.
__sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.
__wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.
For passing data between php and js you would use json_encode to turn php array to valid json format. Or other way round - use JSON.parese() to convert a output data (string) into valid json object. You would want to do that to make use of local storage. (offline data access)

Yes, I can. Assume we need to track your system means In your system has more than one admin and subadmin, All of these can insert or update or edit any information.Later you need to know who make this change. For solving this problem you need serialize.
**Explain:**Create a table named history which stores all changes. Each time there is a change insert a new row in this table. It might have this fields:
history(id,target_table(name of the table), target_id (ID of the saved entry),create/edit/change data (serialized data of the saved row),date)
I hope this will help you.

preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');

Related

To call a particular column/field from an array using PHP [duplicate]

My problem is very basic.
I did not find any example to meet my needs as to what exactly serialize() and unserialize() mean in php? They just give an example - serialize an array and show an output in an unexplained format. It is really hard to understand the basic concept going through their jargon.
EDIT:
<?php
$a= array( '1' => 'elem 1', '2'=> 'elem 2', '3'=>' elem 3');
print_r($a);
echo ("<br></br>");
$b=serialize($a);
print_r($b);
?>
output:
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
I cannot understand the second output. Besides that, can anyone give an example of a situation that I need to serialize a php array before using it?
A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serialize is just a format to express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.
Take for example this common problem:
How do I pass a PHP array to Javascript?
PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript?
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:
{ 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }
Javascript can easily reverse this into an actual Javascript array.
This is just as valid a representation of the same data structure though:
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
But pretty much only PHP uses it, there's little support for this format anywhere else.
This is very common and well supported as well though:
<array>
<element key='1'>elem 1</element>
<element key='2'>elem 2</element>
<element key='3'>elem 3</element>
</array>
There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.
PHP serialize() unserialize() usage
http://freeonlinetools24.com/serialize
echo '<pre>';
// say you have an array something like this
$multidimentional_array= array(
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 4, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 5, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 8, 7)
)
);
// serialize
$serialized_array=serialize($multidimentional_array);
print_r($serialized_array);
Which gives you an output something like this
a:3:{i:0;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:4;i:2;i:7;}}i:1;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:5;i:2;i:7;}}i:2;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:8;i:2;i:7;}}}
again if you want to get the original array back just use PHP unserialize() function
$original_array=unserialize($serialized_array, ['allowed_classes' => false]);
var_export($original_array);
I hope this will help
Note: Set allowed_classes to false in unserialize for security reasons. See Warning https://www.php.net/manual/en/function.unserialize.php
<?php
$a= array("1","2","3");
print_r($a);
$b=serialize($a);
echo $b;
$c=unserialize($b, ['allowed_classes' => false]);
print_r($c);
Run this program its echo the output
a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}
Note: Set allowed_classes to false in unserialize for security reasons.
here
a=size of array
i=count of array number
s=size of array values
you can use serialize to store array of data in database and can retrieve and UN-serialize data to use. See Warning https://www.php.net/manual/en/function.unserialize.php
When you want to make your php value storable, you have to turn it to be a string value, that is what serialize() does. And unserialize() does the reverse thing.
Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.
Instead, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().
If you are familiar with json_encode() and json_decode() (and JSON in general), the concept is similar.
Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.
it makes really difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.
That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.
A good example of serialize() and unserialize() could be like this:
$posts = base64_encode(serialize($_POST));
header("Location: $_SERVER[REQUEST_URI]?x=$posts");
Unserialize on the page
if($_GET['x']) {
// unpack serialize and encoded URL
$_POST = unserialize(base64_decode($_GET['x']));
}
From http://php.net/manual/en/function.serialize.php :
Generates a storable representation of a value.
This is useful for storing or passing PHP values around without losing their type and structure.
Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).
Unserialize is used to convert the string back to an object.
Basically, when you serialize arrays or objects you simply turn it to a valid string format so that you can easily store them outside of the php script.
Use serialize to save the state of an object in database (lets take the User class as an example) Next unserialize the data to load the previous state back to the object (methods are not serializer you need to include object class to be able to use it)
user personalization
Note for object you should use magic __sleep and __wakeup methods.
__sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.
__wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.
For passing data between php and js you would use json_encode to turn php array to valid json format. Or other way round - use JSON.parese() to convert a output data (string) into valid json object. You would want to do that to make use of local storage. (offline data access)
Yes, I can. Assume we need to track your system means In your system has more than one admin and subadmin, All of these can insert or update or edit any information.Later you need to know who make this change. For solving this problem you need serialize.
**Explain:**Create a table named history which stores all changes. Each time there is a change insert a new row in this table. It might have this fields:
history(id,target_table(name of the table), target_id (ID of the saved entry),create/edit/change data (serialized data of the saved row),date)
I hope this will help you.
preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');

How do i format a template string with this kind of data? [duplicate]

My problem is very basic.
I did not find any example to meet my needs as to what exactly serialize() and unserialize() mean in php? They just give an example - serialize an array and show an output in an unexplained format. It is really hard to understand the basic concept going through their jargon.
EDIT:
<?php
$a= array( '1' => 'elem 1', '2'=> 'elem 2', '3'=>' elem 3');
print_r($a);
echo ("<br></br>");
$b=serialize($a);
print_r($b);
?>
output:
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
I cannot understand the second output. Besides that, can anyone give an example of a situation that I need to serialize a php array before using it?
A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serialize is just a format to express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.
Take for example this common problem:
How do I pass a PHP array to Javascript?
PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript?
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:
{ 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }
Javascript can easily reverse this into an actual Javascript array.
This is just as valid a representation of the same data structure though:
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
But pretty much only PHP uses it, there's little support for this format anywhere else.
This is very common and well supported as well though:
<array>
<element key='1'>elem 1</element>
<element key='2'>elem 2</element>
<element key='3'>elem 3</element>
</array>
There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.
PHP serialize() unserialize() usage
http://freeonlinetools24.com/serialize
echo '<pre>';
// say you have an array something like this
$multidimentional_array= array(
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 4, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 5, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 8, 7)
)
);
// serialize
$serialized_array=serialize($multidimentional_array);
print_r($serialized_array);
Which gives you an output something like this
a:3:{i:0;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:4;i:2;i:7;}}i:1;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:5;i:2;i:7;}}i:2;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:8;i:2;i:7;}}}
again if you want to get the original array back just use PHP unserialize() function
$original_array=unserialize($serialized_array, ['allowed_classes' => false]);
var_export($original_array);
I hope this will help
Note: Set allowed_classes to false in unserialize for security reasons. See Warning https://www.php.net/manual/en/function.unserialize.php
<?php
$a= array("1","2","3");
print_r($a);
$b=serialize($a);
echo $b;
$c=unserialize($b, ['allowed_classes' => false]);
print_r($c);
Run this program its echo the output
a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}
Note: Set allowed_classes to false in unserialize for security reasons.
here
a=size of array
i=count of array number
s=size of array values
you can use serialize to store array of data in database and can retrieve and UN-serialize data to use. See Warning https://www.php.net/manual/en/function.unserialize.php
When you want to make your php value storable, you have to turn it to be a string value, that is what serialize() does. And unserialize() does the reverse thing.
Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.
Instead, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().
If you are familiar with json_encode() and json_decode() (and JSON in general), the concept is similar.
Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.
it makes really difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.
That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.
A good example of serialize() and unserialize() could be like this:
$posts = base64_encode(serialize($_POST));
header("Location: $_SERVER[REQUEST_URI]?x=$posts");
Unserialize on the page
if($_GET['x']) {
// unpack serialize and encoded URL
$_POST = unserialize(base64_decode($_GET['x']));
}
From http://php.net/manual/en/function.serialize.php :
Generates a storable representation of a value.
This is useful for storing or passing PHP values around without losing their type and structure.
Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).
Unserialize is used to convert the string back to an object.
Basically, when you serialize arrays or objects you simply turn it to a valid string format so that you can easily store them outside of the php script.
Use serialize to save the state of an object in database (lets take the User class as an example) Next unserialize the data to load the previous state back to the object (methods are not serializer you need to include object class to be able to use it)
user personalization
Note for object you should use magic __sleep and __wakeup methods.
__sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.
__wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.
For passing data between php and js you would use json_encode to turn php array to valid json format. Or other way round - use JSON.parese() to convert a output data (string) into valid json object. You would want to do that to make use of local storage. (offline data access)
Yes, I can. Assume we need to track your system means In your system has more than one admin and subadmin, All of these can insert or update or edit any information.Later you need to know who make this change. For solving this problem you need serialize.
**Explain:**Create a table named history which stores all changes. Each time there is a change insert a new row in this table. It might have this fields:
history(id,target_table(name of the table), target_id (ID of the saved entry),create/edit/change data (serialized data of the saved row),date)
I hope this will help you.
preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');

How to use php serialize() and unserialize()

My problem is very basic.
I did not find any example to meet my needs as to what exactly serialize() and unserialize() mean in php? They just give an example - serialize an array and show an output in an unexplained format. It is really hard to understand the basic concept going through their jargon.
EDIT:
<?php
$a= array( '1' => 'elem 1', '2'=> 'elem 2', '3'=>' elem 3');
print_r($a);
echo ("<br></br>");
$b=serialize($a);
print_r($b);
?>
output:
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
I cannot understand the second output. Besides that, can anyone give an example of a situation that I need to serialize a php array before using it?
A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a "lower common denominator" that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function serialize is just a format to express such a thing, it serializes a data structure into a string representation that's unique to PHP and can be reversed into a PHP object using unserialize. There are many other formats though, like JSON or XML.
Take for example this common problem:
How do I pass a PHP array to Javascript?
PHP and Javascript can only communicate via strings. You can pass the string "foo" very easily to Javascript. You can pass the number 1 very easily to Javascript. You can pass the boolean values true and false easily to Javascript. But how do you pass this array to Javascript?
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:
{ 1 : 'elem 1', 2 : 'elem 2', 3 : 'elem 3' }
Javascript can easily reverse this into an actual Javascript array.
This is just as valid a representation of the same data structure though:
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
But pretty much only PHP uses it, there's little support for this format anywhere else.
This is very common and well supported as well though:
<array>
<element key='1'>elem 1</element>
<element key='2'>elem 2</element>
<element key='3'>elem 3</element>
</array>
There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.
PHP serialize() unserialize() usage
http://freeonlinetools24.com/serialize
echo '<pre>';
// say you have an array something like this
$multidimentional_array= array(
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 4, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 5, 7)
),
array(
array("rose", 1.25, 15),
array("daisy", 0.75, 25),
array("orchid", 8, 7)
)
);
// serialize
$serialized_array=serialize($multidimentional_array);
print_r($serialized_array);
Which gives you an output something like this
a:3:{i:0;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:4;i:2;i:7;}}i:1;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:5;i:2;i:7;}}i:2;a:3:{i:0;a:3:{i:0;s:4:"rose";i:1;d:1.25;i:2;i:15;}i:1;a:3:{i:0;s:5:"daisy";i:1;d:0.75;i:2;i:25;}i:2;a:3:{i:0;s:6:"orchid";i:1;i:8;i:2;i:7;}}}
again if you want to get the original array back just use PHP unserialize() function
$original_array=unserialize($serialized_array, ['allowed_classes' => false]);
var_export($original_array);
I hope this will help
Note: Set allowed_classes to false in unserialize for security reasons. See Warning https://www.php.net/manual/en/function.unserialize.php
<?php
$a= array("1","2","3");
print_r($a);
$b=serialize($a);
echo $b;
$c=unserialize($b, ['allowed_classes' => false]);
print_r($c);
Run this program its echo the output
a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}
Note: Set allowed_classes to false in unserialize for security reasons.
here
a=size of array
i=count of array number
s=size of array values
you can use serialize to store array of data in database and can retrieve and UN-serialize data to use. See Warning https://www.php.net/manual/en/function.unserialize.php
When you want to make your php value storable, you have to turn it to be a string value, that is what serialize() does. And unserialize() does the reverse thing.
Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.
Instead, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().
If you are familiar with json_encode() and json_decode() (and JSON in general), the concept is similar.
Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.
it makes really difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.
That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.
A good example of serialize() and unserialize() could be like this:
$posts = base64_encode(serialize($_POST));
header("Location: $_SERVER[REQUEST_URI]?x=$posts");
Unserialize on the page
if($_GET['x']) {
// unpack serialize and encoded URL
$_POST = unserialize(base64_decode($_GET['x']));
}
From http://php.net/manual/en/function.serialize.php :
Generates a storable representation of a value.
This is useful for storing or passing PHP values around without losing their type and structure.
Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).
Unserialize is used to convert the string back to an object.
Basically, when you serialize arrays or objects you simply turn it to a valid string format so that you can easily store them outside of the php script.
Use serialize to save the state of an object in database (lets take the User class as an example) Next unserialize the data to load the previous state back to the object (methods are not serializer you need to include object class to be able to use it)
user personalization
Note for object you should use magic __sleep and __wakeup methods.
__sleep is called by serialize(). A sleep method will return an array of the values from the object that you want to persist.
__wakeup is called by unserialize(). A wakeup method should take the unserialized values and initialize them in them in the object.
For passing data between php and js you would use json_encode to turn php array to valid json format. Or other way round - use JSON.parese() to convert a output data (string) into valid json object. You would want to do that to make use of local storage. (offline data access)
Yes, I can. Assume we need to track your system means In your system has more than one admin and subadmin, All of these can insert or update or edit any information.Later you need to know who make this change. For solving this problem you need serialize.
**Explain:**Create a table named history which stores all changes. Each time there is a change insert a new row in this table. It might have this fields:
history(id,target_table(name of the table), target_id (ID of the saved entry),create/edit/change data (serialized data of the saved row),date)
I hope this will help you.
preg_match_all('/\".*?\"/i', $string, $matches);
foreach ($matches[0] as $i => $match) $matches[$i] = trim($match, '"');

Declaring static arrays in php

I am new to php. I was wondering how I could declare a static array in php. Here is what I would do in C. How is the corresponding php code for it?
char a[][] = { (1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3) };
From what I read it has to be something like this -
$a = array( 1 => array(1,1), 2 => array(1,2), ... );
Is this correct? If so it sucks :) I hope I am wrong.
Thanks,
- Pav
You've already found the way to do it natively.
Another option would be to declare your data as JSON (a very concise and human-friendly format). This could be either in a separate file bundled with your app, or directly in your code in a string. Then parse the JSON at runtime. Since PHP isn't exactly known for speed, this may or may not make your noticeably app slower to start.
you have it already figured out in your question.
One thing I would add is that you do not need to explicitly define the keys if you are intending to use a zero based array, this is assumed and can be done like so...
$a = array(array(1,1),array(1,2), ... );
You can also use what is called associative arrays which use string keys and you define them the same way you do in your example, except use strings instead of numbers...
$ass_array = array( 'array_1' => array(1,1), 'array_2' => array(1,2), ... );
you would then call your associative array like this...
$ass_array['array_1'];
Also, if you want to append single items to an array (for example in a loop to load an array)...
$ass_array[] = $item;
Further to jondavidjohn's anwser, you could just write a quick script to grab your list of values and generate the array statement for you.
No need to care how verbose the syntax is then. If the task is long and repetitious enough to care, don't do it by hand. :)

Don't understand serialize()

I'm looking at this function: serialize() for PHP and I don't really understand what is it's function. Can someone provide a simple example with output?
Basically, the goal of serialize is to transform any (alsmost) kind of data to a string, so it can be transmitted, stored, ...
A quick example :
$my_array = array(
'a' => 10,
'glop' => array('test', 'blah'),
);
$serialized = serialize($my_array);
echo $serialized;
Will get you this output :
a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}
And, later, you can unserialize that string, to get the original data back :
$serialized = 'a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}';
$data = unserialize($serialized);
var_dump($data);
Will get you :
array
'a' => int 10
'glop' =>
array
0 => string 'test' (length=4)
1 => string 'blah' (length=4)
Common uses include :
Ability to transmit (almost) any kind of PHP data from one PHP script to another
Ability to store (almost) any kind of PHP data in a single database field -- even if it's not quite a good practice on the database-side, it can sometimes be usefull
Ability to store data in some caching mecanism (APC, memcached, files, ...), in which you can only store strings
Note, though, that using serialize is great when you are only working with PHP (as it's a PHP-specific format, that's able to work with almost any kind of PHP data, and is really fast) ; but it's not that great when you have to also work with something else than PHP (as it's PHP-specific). In those cases, you can use XML, JSON (see json_encode and json_decode), ...
In the PHP manual, you can also read the Object Serialization section, btw.
If you want to save an array or object normalised in a database row for example, serialize() (and unserialize()) are your friends, because you can't store an array or object flattened without first turning it into a string.
json_encode() and json_decode() are similar except they encode as JSON.
See this example, should be pretty clear.

Categories