6

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?

10
  • 4
    "an error", doesn't tell us much. Please quote the error! Commented Apr 1, 2012 at 19:43
  • Of course, sorry! The error is: Parse error: syntax error, unexpected T_VARIABLE Commented Apr 1, 2012 at 19:47
  • On which line does that error occur? Commented Apr 1, 2012 at 19:48
  • after or before array_key_exists? Commented Apr 1, 2012 at 19:49
  • 1
    All your semicolons are in the right place? i.e. there is no semicolon missing on the line before the erroneous line? Commented Apr 1, 2012 at 19:52

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

-1
echo $unser[1901];

should be

echo $unser['1901'];

Also you can do

if(isset($unser['1901'])) { }

instead of array_key_esists()

5 Comments

Correct, but not 100%. Some times, PHP recognize you are doing some mistakes and know 1901 is not a constant.
$unser[1901] is completely fine. And array_key_exists() and isset() are not the same in this case.
That didn't work unfortunately. Now the error is Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING
Post more source code. Error is probably happening 1 line before posted code.
It's strange that's all the code there is between the echo that works fine and the search_array I initially tried

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.