Programing

잘못된 문자열 오프셋 경고 PHP

lottogame 2020. 5. 24. 10:45
반응형

잘못된 문자열 오프셋 경고 PHP


PHP 버전을 5.4.0-3으로 업데이트 한 후 이상한 PHP 오류가 발생합니다.

이 배열이 있습니다.

Array
(
    [host] => 127.0.0.1
    [port] => 11211
)

이와 같이 액세스하려고하면 이상한 경고가 나타납니다.

 print $memcachedConfig['host'];
 print $memcachedConfig['port'];


 Warning: Illegal string offset 'host' in ....
 Warning: Illegal string offset 'port' in ...

php.ini를 편집하고 오류 수준을 다시 설정하고 싶지 않습니다.


이 방법으로 시도하십시오 ....이 코드를 테스트했습니다 .... 작동합니다 ....

$memcachedConfig = array("host" => "127.0.0.1","port" => "11211");
print_r ($memcachedConfig['host']);

오류는 Illegal string offset 'whatever' in...일반적으로 문자열을 전체 배열로 사용하려고한다는 것을 의미합니다.

실제로 문자열은 PHP에서 단일 문자의 배열로 취급 될 수 있기 때문에 가능합니다. 따라서 $ var은 키가있는 배열이지만 표준 숫자 키가 있는 문자열 일뿐입니다 .

$fruit_counts = array('apples'=>2, 'oranges'=>5, 'pears'=>0);
echo $fruit_counts['oranges']; // echoes 5
$fruit_counts = "an unexpected string assignment";
echo $fruit_counts['oranges']; // causes illegal string offset error

http://ideone.com/fMhmkR 에서 실제로 볼 수 있습니다.

이 질문에 온 사람들은 오류의 모호성을 내가했던 것처럼 그것을 할 수있는 것으로 바꾸려고합니다.


TL; DR

stringa 키가있는 배열 인 것처럼 a에 액세스하려고 합니다 string. string이해하지 못할 것입니다. 코드에서 우리는 문제를 볼 수 있습니다 :

"hello"["hello"];
// PHP Warning:  Illegal string offset 'hello' in php shell code on line 1

"hello"[0];
// No errors.

array("hello" => "val")["hello"];
// No errors. This is *probably* what you wanted.

깊이

그 오류를 보자.

경고 : 잘못된 문자열 오프셋 'port'...

그것은 무엇을 말하는가? 문자열을 문자열 'port'의 오프셋으로 사용하려고 합니다. 이처럼 :

$a_string = "string";

// This is ok:
echo $a_string[0]; // s
echo $a_string[1]; // t
echo $a_string[2]; // r
// ...

// !! Not good:
echo $a_string['port'];
// !! Warning: Illegal string offset 'port' in ...

무엇이 원인입니까?

어떤 이유로 당신은을 기대 array했지만 string. 그냥 섞어. 아마도 변수가 변경되었을 수도 있고, 결코 변하지 않았을 수도 있습니다 array. 정말 중요하지 않습니다.

무엇을 할 수 있습니까?

If we know we should have an array, we should do some basic debugging to determine why we don't have an array. If we don't know if we'll have an array or string, things become a bit trickier.

What we can do is all sorts of checking to ensure we don't have notices, warnings or errors with things like is_array and isset or array_key_exists:

$a_string = "string";
$an_array = array('port' => 'the_port');

if (is_array($a_string) && isset($a_string['port'])) {
    // No problem, we'll never get here.
    echo $a_string['port'];
}

if (is_array($an_array) && isset($an_array['port'])) {
    // Ok!
    echo $an_array['port']; // the_port
}

if (is_array($an_array) && isset($an_array['unset_key'])) {
    // No problem again, we won't enter.
    echo $an_array['unset_key'];
}


// Similar, but with array_key_exists
if (is_array($an_array) && array_key_exists('port', $an_array)) {
    // Ok!
    echo $an_array['port']; // the_port
}

There are some subtle differences between isset and array_key_exists. For example, if the value of $array['key'] is null, isset returns false. array_key_exists will just check that, well, the key exists.


There are a lot of great answers here - but I found my issue was quite a bit more simple.

I was trying to run the following command:

$x['name']   = $j['name'];

and I was getting this illegal string error on $x['name'] because I hadn't defined the array first. So I put the following line of code in before trying to assign things to $x[]:

$x = array();

and it worked.


A little bit late to the question, but for others who are searching: I got this error by initializing with a wrong value (type):

$varName = '';
$varName["x"] = "test"; // causes: Illegal string offset

The right way is:

 $varName = array();
 $varName["x"] = "test"; // works

As from PHP 5.4 we need to pass the same datatype value that a function expects. For example:

function testimonial($id); // This function expects $id as an integer

When invoking this function, if a string value is provided like this:

$id = $array['id']; // $id is of string type
testimonial($id); // illegal offset warning

This will generate an illegal offset warning because of datatype mismatch. In order to solve this, you can use settype:

$id = settype($array['id'],"integer"); // $id now contains an integer instead of a string
testimonial($id); // now running smoothly

Before to check the array, do this:

if(!is_array($memcachedConfig))
     $memcachedConfig = array();

In my case i change mysql_fetch_assoc to mysql_fetch_array and solve. It takes 3 days to solve :-( and the other versions of my proyect run with fetch assoc.


just use

$memcachedConfig = array();

before

 print $memcachedConfig['host'];
 print $memcachedConfig['port'];


 Warning: Illegal string offset 'host' in ....
 Warning: Illegal string offset 'port' in ....

this is because you never define what is $memcachedConfig, so by default are treated by string not arrays..


Just incase it helps anyone, I was getting this error because I forgot to unserialize a serialized array. That's definitely something I would check if it applies to your case.


It's an old one but in case someone can benefit from this. You will also get this error if your array is empty.

In my case I had:

$buyers_array = array();
$buyers_array = tep_get_buyers_info($this_buyer_id); // returns an array
...
echo $buyers_array['firstname'] . ' ' . $buyers_array['lastname']; 

which I changed to:

$buyers_array = array();
$buyers_array = tep_get_buyers_info($this_buyer_id); // returns an array
...
if(is_array($buyers_array)) {
   echo $buyers_array['firstname'] . ' ' . $buyers_array['lastname']; 
} else {
   echo 'Buyers id ' . $this_buyer_id . ' not found';
}

In my case, I solved it when I changed in function that does sql query after: return json_encode($array) then: return $array


It works to me:

Testing Code of mine:

$var2['data'] = array ('a'=>'21','b'=>'32','c'=>'55','d'=>'66','e'=>'77');
foreach($var2 as $result)
{  
    $test = $result['c'];
}
print_r($test);

Output: 55

Check it guys. Thanks


I solved this problem by using trim() function. the issue was with space.

so lets try

$unit_size = []; //please declare the variable type 
$unit_size = exolode("x", $unit_size);
$width  = trim ($unit_size[1] );
$height = trim ($unit_size[2] );

I hope this will help you.


i think the only reason for this message is because target Array is actually an array like string etc (JSON -> {"host": "127.0.0.1"}) variable


For PHP

//Setup Array like so
$memcachedConfig = array(
  "host" => "127.0.0.1",
  "port" => "11211"
);

//Always a good practice to check if empty

if(isset($memcachedConfig['host']) && isset($memcachedConfig['port'])){

    //Some codes

    print_r ($memcachedConfig['host']);
    print_r ($memcachedConfig['port']);

}

Just make sure to check that the value returning is not empty. So this example was for PHP so find out how to check if an array is empty in other languages.

참고URL : https://stackoverflow.com/questions/9869150/illegal-string-offset-warning-php

반응형