Reputation: 3514
I have the following php code that gets a serialized array from a mysql database, then unserializes it. This is working fine. The following code:
$row=mysql_fetch_array($result);
$mydata=$row[0];
$unser=unserialize($mydata);
echo "$mydata<br>";
print_r($unser);
echo "<br>";
echo $unser[1901];
The output is this:
a:2:{i:2070;s:4:"0.00";i:1901;s:4:"1.00";}
Array ( [2070] => 0.00 [1901] => 1.00 )
1.00
So far, so good. Now, I'm trying to write the code so that it checks if the array key 1901 exists. For that, I tried this:
$search_array = $unser;
if (array_key_exists('1901', $search_array)) {
echo "The key 1901 is in the array";
}
However that is returning an error. What am I doing wrong?
Upvotes: 6
Views: 1195
Reputation: 4974
With the following code:
$mydata= 'a:2:{i:2070;s:4:"0.00";i:1901;s:4:"1.00";}';
$unser=unserialize($mydata);
echo "$mydata<br>";
print_r($unser);
echo "<br>";
echo $unser['1901'];
$search_array = $unser;
if (array_key_exists('1901', $search_array)) {
echo "<br />The key 1901 is in the array";
}
It will work correctly:
a:2:{i:2070;s:4:"0.00";i:1901;s:4:"1.00";}
Array ( [2070] => 0.00 [1901] => 1.00 )
1.00
The key 1901 is in the array
Check if you have more code after the lines of code you have posted. I think is another piece of code which is confusing you.
Upvotes: 4
Reputation: 4361
echo $unser[1901];
should be
echo $unser['1901'];
Also you can do
if(isset($unser['1901'])) { }
instead of array_key_esists()
Upvotes: -1