0

When I run this code I found on Perfect money website, it caused

PHP Warning: Illegal string offset 'ERROR' in line 33

can you please someone explain me why? - btw. Line 33 is: $ar[$key]=$item[2];

Here is the code:

<?php

/*

This script demonstrates transfer proccess between two
PerfectMoney accounts using PerfectMoney API interface.

*/

// trying to open URL to process PerfectMoney Spend request
$f=fopen('https://perfectmoney.is/acct/confirm.asp?AccountID=myaccount&PassPhrase=mypassword&Payer_Account=U987654&Payee_Account=U1234567&Amount=1&PAY_IN=1&PAYMENT_ID=1223', 'rb');

if($f===false){
   echo 'error openning url';
}

// getting data
$out=array(); $out="";
while(!feof($f)) $out.=fgets($f);

fclose($f);

// searching for hidden fields
if(!preg_match_all("/<input name='(.*)' type='hidden' value='(.*)'>/", $out, $result, PREG_SET_ORDER)){
   echo 'Ivalid output';
   exit;
}

$ar="";
foreach($result as $item){
   $key=$item[1];
   $ar[$key]=$item[2];
}

echo '<pre>';
print_r($ar);
echo '</pre>';



?>

I am running this on PHP 7.1

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
Farer
  • 25
  • 1
  • 5
  • 2
    `$ar` is a string, not an array. – Dormilich May 02 '18 at 14:02
  • @Dormilich Thanks for reply, but do you know how to fix that code? I also see there is an error. – Farer May 02 '18 at 14:03
  • 1
    Initialise `$ar` as array and not as string. – Dormilich May 02 '18 at 14:05
  • 1
    Possible duplicate of [Illegal string offset Warning PHP](https://stackoverflow.com/questions/9869150/illegal-string-offset-warning-php) – Ricardo Pontual May 02 '18 at 14:05
  • @Dormilich can you please write me a correct code? I am dumb for it! Thanks! – Farer May 02 '18 at 14:07
  • _Side note:_ You're echoing an error message if `$f` is false, but then you continue with your code anyway, assuming that `$f` is a valid file pointer resource? – M. Eriksson May 02 '18 at 14:09
  • @Magnus Eriksson that part of code is not important to me, I am not using it on my site, anyway, thanks! i've fixed what I need, ThomasVdBerge helped me, thanks again! – Farer May 02 '18 at 14:12

1 Answers1

1

In your code, you are first declaring $ar as a string:

$ar="";

Then you are using it as an array:

foreach($result as $item){
   $key=$item[1];
   $ar[$key]=$item[2];
}

You could resolve this warning by changing

$ar="";

to one of the following:

$ar=[]; // Short array declaration

$ar = array(); // Long array syntax declaration

 // Remove the line altogether, PHP can handle this.
ThomasVdBerge
  • 7,483
  • 4
  • 44
  • 62
  • 1
    Or simply remove the line altogether. There is no need to declare the variable prior to using it in this case – Andreas May 02 '18 at 14:13