Illegal offset type in ошибка

I’m getting

illegal offset type

error for every iteration of this code. Here’s the code :

$s = array();
for($i = 0; $i < 20; $i++){
    $source = $xml->entry[$i]->source;
    $s[$source] += 1;    
}

print_r($s)

Jignesh Joisar's user avatar

asked Apr 28, 2010 at 19:15

Steven's user avatar

1

Illegal offset type errors occur when you attempt to access an array index using an object or an array as the index key.

Example:

$x = new stdClass();
$arr = array();
echo $arr[$x];
//illegal offset type

Your $xml array contains an object or array at $xml->entry[$i]->source for some value of $i, and when you try to use that as an index key for $s, you get that warning. You’ll have to make sure $xml contains what you want it to and that you’re accessing it correctly.

answered Apr 28, 2010 at 19:22

zombat's user avatar

zombatzombat

92.4k24 gold badges156 silver badges164 bronze badges

6

Use trim($source) before $s[$source].

Mat's user avatar

Mat

201k40 gold badges392 silver badges405 bronze badges

answered Nov 11, 2011 at 10:00

Zafer's user avatar

ZaferZafer

2613 silver badges2 bronze badges

4

check $xml->entry[$i] exists and is an object
before trying to get a property of it

 if(isset($xml->entry[$i]) && is_object($xml->entry[$i])){
   $source = $xml->entry[$i]->source;          
   $s[$source] += 1;
 }

or $source might not be a legal array offset but an array, object, resource or possibly null

answered Apr 28, 2010 at 19:24

brian_d's user avatar

brian_dbrian_d

11.1k5 gold badges47 silver badges72 bronze badges

1

There are probably less than 20 entries in your xml.

change the code to this

for ($i=0;$i< sizeof($xml->entry); $i++)
...

answered Apr 28, 2010 at 19:17

Byron Whitlock's user avatar

Byron WhitlockByron Whitlock

52.4k28 gold badges123 silver badges168 bronze badges

1

I had a similar problem. As I got a Character from my XML child I had to convert it first to a String (or Integer, if you expect one). The following shows how I solved the problem.

foreach($xml->children() as $newInstr){
        $iInstrument = new Instrument($newInstr['id'],$newInstr->Naam,$newInstr->Key);
        $arrInstruments->offsetSet((String)$iInstrument->getID(), $iInstrument);
    }

answered Jul 29, 2017 at 20:04

user8387356's user avatar

Posted on Oct 18, 2022


PHP illegal offset type error occurs when you try to access an array using an object or an array as the key.

The PHP array keys are defined using string or int data type as shown below:

<?php
$user[0] = "Nathan";
$user[1] = "Jane";
$user["three"] = "John";

$obj = new stdClass();

print $user[0];
print $user[$obj]; // error

When you try to access an array using $obj as shown in the example above, PHP will throw the illegal offset type error:

Fatal error: Uncaught TypeError: Illegal offset type
  in /home/code.php:9

To resolve this error, you need to make sure that you are accessing the array correctly.

This error also frequently occurs when you are iterating over an array as follows:

<?php
$keys = [0, 1, new StdClass(), 2];

$array = ["Nathan", "John", "Jane", "Mary"];

foreach ($keys as $key) {
    print $array[$key] . PHP_EOL; // error
}

Because there is an object in the $keys array, PHP will throw the illegal offset type error when the iteration reaches that object.

You can use print_r() or var_dump() to check on the values of $keys in the example above:

You need to see the values of the $keys variable and make sure that you are not using an object or an array. The above code will show the following output:

Array
(
    [0] => 0
    [1] => 1
    [2] => stdClass Object
        (
        )
    [3] => 2
)

Once you see the value that causes the error, you need to remove it from your $keys array.

And that’s how you solve the PHP illegal offset type error.

За последние 24 часа нас посетили 12434 программиста и 897 роботов. Сейчас ищут 726 программистов …


  1. TeslaFeo

    С нами с:
    9 мар 2016
    Сообщения:
    2.995
    Симпатии:
    759

    Приветствую, уважаемые форумчане!
    Объясните, плз, криворучке, почему при объявлении массива:

    он получает Illegal offset type (недопустимый тип смещения) в каждой строке, кроме первой и последней.
    Заранее благодарю!


  2. Maputo

    Maputo
    Активный пользователь

    С нами с:
    30 июл 2015
    Сообщения:
    1.136
    Симпатии:
    173

    А зачем у Вас квадратные скобки?


    TeslaFeo и denis01 нравится это.


  3. denis01

    Команда форума
    Модератор

    У меня ошибок не выдаёт, ты с [ и ] выполняешь?


  4. mkramer

    Команда форума
    Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.522
    Симпатии:
    1.744

    Потому что индексы могут быть числами или строками, но не массивами


    TeslaFeo и denis01 нравится это.


  5. TeslaFeo

    С нами с:
    9 мар 2016
    Сообщения:
    2.995
    Симпатии:
    759

    я понял. PHP принял их за массивы.
    От куда у меня в голове эти квадратные скобки)


  6. Maputo

    Maputo
    Активный пользователь

    С нами с:
    30 июл 2015
    Сообщения:
    1.136
    Симпатии:
    173

    @TeslaFeo
    А не пробовали так объявлять:

    1. 45 => [ [ 0, 1 ], [ 0, 1 ] ],
    2. 46 => [ [ 0, 1, 2 ], [ 0 ] ],
    3. 40 => [ [ 0, 1, 2 ], [ 0 ] ],
    4. 41 => [ [ 0, 1, 2 ], [ 0, 1, 2 ] ],
    5. 43 => [ [ 0, 1, 2 ], [ 0, 1 ] ],
    6. 44 => [ [ 0, 1, 2 ], [ 0, 1, 2 ] ],
    7. 47 => [ [ 0, 1, 2 ], [ 0, 1, 2 ] ]

    Мне кажется так лучше читается структура и содержимое.

Submitted by oretnom23 on Thursday, May 4, 2023 — 16:39.

How to fix the PHP "Illegal offset type" error

If you are currently facing a «Fatal error: Uncaught TypeError: Illegal offset type in …» error in your PHP code or script, this article can help you to solve this kind of PHP error.

PHP‘s Illegal offset Type error occurs when you are trying to use a full object or array as the key of an array. PHP array keys can only be a string or integer type.

Example #1

Let’s assume that we the following PHP code:

  1. <?php

  2. $myArray = [

  3. "key1" => "My Array Value 1",

  4. "key2" => "My Array Value 2",

  5. "key3" => "My Array Value 3"

  6. ];

  7. echo $myArray[$keys];

  8. ?>

In the PHP script above, we have an array with 3 items which have the key1, key2, and key3 keys. Each item has values which are «My Array Value 1» for «keys1», «My Array Value 2» for «keys2», and «My Array Value 3» for «keys3». The script will result in the following:

PHP Illegal offset type solved

The error occurred because we are trying to echo or output something from the $myArray array with a full array as the key. To fix this Illegal offset type error, we should specify the exact array key to the $keys to get the value that we want and the value of the array with the specific key will serve as the key of the $myArray.

Here’s the sample script that solves the Illegal offset type error on the code.

  1. <?php

  2. $myArray = [

  3. "key1" => "My Array Value 1",

  4. "key2" => "My Array Value 2",

  5. "key3" => "My Array Value 3"

  6. ];

  7. echo $myArray[$keys[0]]."<br/>";// output: My Array Value 1

  8. echo $myArray[$keys[1]]."<br/>";// output: My Array Value 2

  9. echo $myArray[$keys[2]];// output: My Array Value 3

  10. ?>

PHP Illegal offset type solved

Example #2

The Illegal offset error might also occur if we unintentionally overwrite the value of a variable with an array. You must consider also to check the given variable to your array key has the right value that you intended to be returned.

Assuming that your PHP code is like the following.

  1. <?php

  2. $myArray = [

  3. "key1" => "My Array Value 1",

  4. "key2" => "My Array Value 2",

  5. "key3" => "My Array Value 3"

  6. ];

  7. $sampleVar = 'key1';

  8. // Unintended variable overwrite

  9. $sampleVar = [];

  10. echo $myArray[$sampleVar];

  11. ?>

Result

To solve this, we can either replace the variable name of the duplicate variable that causes the error with a unique variable or remove the duplicate variable if it is not in use. Check out the following fixed PHP script below.

  1. <?php

  2. $myArray = [

  3. "key1" => "My Array Value 1",

  4. "key2" => "My Array Value 2",

  5. "key3" => "My Array Value 3"

  6. ];

  7. $sampleVar = 'key1';

  8. // Replaced duplicate variable form $sampleVar into $sampleVar2

  9. $sampleVar2 = [];

  10. echo $myArray[$sampleVar];

  11. ?>

That’s how you solve the Illegal offset. You can also leave a comment with any question or query about the PHP error you are currently and we’ll try to help you find the solution.

That’s it! I hope this How to Fix the PHP «Illegal offset type» error Tutorial will help you with what you are looking for.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

  • 58 views

[2018-10-21 00:37:27] Local.ERROR: Illegal offset type in isset or empty {"userId":3,"email":"rxxxxx@xxxx","exception":"[object] (ErrorException(code: 0): Illegal offset type in isset or empty at /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Support/NamespacedItemResolver.php:25) [stacktrace] #0 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Support/NamespacedItemResolver.php(25): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'Illegal offset ...', '/home/vagrant/c...', 25, Array) #1 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Translation/Translator.php(376): Illuminate\Support\NamespacedItemResolver->parseKey(Object(Illuminate\Http\Request)) #2 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Translation/Translator.php(116): Illuminate\Translation\Translator->parseKey(Object(Illuminate\Http\Request)) #3 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Translation/Translator.php(102): Illuminate\Translation\Translator->get(Object(Illuminate\Http\Request), Array, NULL) #4 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php(914): Illuminate\Translation\Translator->trans(Object(Illuminate\Http\Request), Array, NULL) #5 /home/vagrant/code/tripwatch/app/Http/Controllers/Auth/ResetPasswordController.php(48): trans(Object(Illuminate\Http\Request)) #6 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Foundation/Auth/ResetsPasswords.php(55): App\Http\Controllers\Auth\ResetPasswordController->sendResetResponse(Object(Illuminate\Http\Request), 'passwords.reset') #7 [internal function]: App\Http\Controllers\Auth\ResetPasswordController->reset(Object(Illuminate\Http\Request)) #8 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): call_user_func_array(Array, Array) #9 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(45): Illuminate\Routing\Controller->callAction('reset', Array) #10 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Route.php(212): Illuminate\Routing\ControllerDispatcher->dispatch(Object(Illuminate\Routing\Route), Object(App\Http\Controllers\Auth\ResetPasswordController), 'reset') #11 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Route.php(169): Illuminate\Routing\Route->runController() #12 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Router.php(679): Illuminate\Routing\Route->run() #13 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(30): Illuminate\Routing\Router->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #14 /home/vagrant/code/tripwatch/app/Http/Middleware/RedirectIfAuthenticated.php(24): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #15 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): App\Http\Middleware\RedirectIfAuthenticated->handle(Object(Illuminate\Http\Request), Object(Closure)) #16 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #17 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(41): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #18 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\Routing\Middleware\SubstituteBindings->handle(Object(Illuminate\Http\Request), Object(Closure)) #19 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #20 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(75): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #21 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure)) #22 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #23 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #24 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\View\Middleware\ShareErrorsFromSession->handle(Object(Illuminate\Http\Request), Object(Closure)) #25 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #26 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(63): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #27 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), Object(Closure)) #28 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #29 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #30 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), Object(Closure)) #31 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #32 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(66): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #33 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), Object(Closure)) #34 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #35 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(104): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #36 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Router.php(681): Illuminate\Pipeline\Pipeline->then(Object(Closure)) #37 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Router.php(656): Illuminate\Routing\Router->runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request)) #38 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Router.php(622): Illuminate\Routing\Router->runRoute(Object(Illuminate\Http\Request), Object(Illuminate\Routing\Route)) #39 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Router.php(611): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request)) #40 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(176): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request)) #41 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(30): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request)) #42 /home/vagrant/code/tripwatch/vendor/fideloper/proxy/src/TrustProxies.php(57): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #43 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Fideloper\Proxy\TrustProxies->handle(Object(Illuminate\Http\Request), Object(Closure)) #44 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #45 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(31): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #46 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure)) #47 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #48 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(31): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #49 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure)) #50 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #51 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #52 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\Foundation\Http\Middleware\ValidatePostSize->handle(Object(Illuminate\Http\Request), Object(Closure)) #53 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #54 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(62): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #55 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure)) #56 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #57 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(104): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #58 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(151): Illuminate\Pipeline\Pipeline->then(Object(Closure)) #59 /home/vagrant/code/tripwatch/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(116): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request)) #60 /home/vagrant/code/tripwatch/public/index.php(55): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request)) #61 {main} "}

Понравилась статья? Поделить с друзьями:
  • Ilife v55 ошибка е06 что делать
  • Ilife v55 pro ошибка е12
  • Ilife v55 pro ошибка е10
  • Ilife v55 pro ошибка e10
  • Ilife v55 pro ошибка e06