CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

21 October, 2020

How to sort an array of associative arrays by value of a given key in PHP?

 Programing Coderfunda     October 21, 2020     No comments   

 

How to sort an array of associative arrays by value of a given key in PHP?

 

11 years ago

Active 2 months ago
Viewed 484k times
470

Given this array:

$inventory = array(

array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),

);

I would like to sort $inventory's elements by price to get:

$inventory = array(

array("type"=>"pork", "price"=>5.43),
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),

);

How can I do this?

 

19 Answers

638

You are right, the function you're looking for is array_multisort().

Here's an example taken straight from the manual and adapted to your case:

$price = array();
foreach ($inventory as $key => $row)
{
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);

As of PHP 5.5.0 you can use array_column() instead of that foreach:

$price = array_column($inventory, 'price');

array_multisort($price, SORT_DESC, $inventory);

 

 Answer

42

Since your array elements are arrays themselves with string keys, your best bet is to define a custom comparison function. It's pretty quick and easy to do. Try this:

function invenDescSort($item1,$item2)
{
if ($item1['price'] == $item2['price']) return 0;
return ($item1['price'] < $item2['price']) ? 1 : -1;
}
usort($inventory,'invenDescSort');
print_r($inventory);

Produces the following:

Array
(
[0] => Array
(
[type] => pork
[price] => 5.43
)

[1] => Array
(
[type] => fruit
[price] => 3.5
)

[2] => Array
(
[type] => milk
[price] => 2.9
)

)

 

Combining with some of the other comments here (uasort and inline anonymous functions), you get this one-liner: uasort( $inventory, function ($a, $b) { if ( $a==$b ) return 0; else return ($a > $b) ? -1 : 1; });

 

25

I ended on this:

function sort_array_of_array(&$array, $subfield)
{
$sortarray = array();
foreach ($array as $key => $row)
{
$sortarray[$key] = $row[$subfield];
}

array_multisort($sortarray, SORT_ASC, $array);
}

Just call the function, passing the array and the name of the field of the second level array. Like:

sort_array_of_array($inventory, 'price');
 
 

19

You can use usort with anonymous function, e.g.

usort($inventory, function ($a, $b) { return strnatcmp($a['price'], $b['price']); });
 
 

5

I use uasort like this

<?php
$users = [
[
'username' => 'joe',
'age' => 11
],
[
'username' => 'rakoto',
'age' => 21
],
[
'username' => 'rabe',
'age' => 17
],
[
'username' => 'fy',
'age' => 19
],
];


uasort($users, function ($item, $compare) {
return $item['username'] >= $compare['username'];
});

var_dump($users);
 
3

This function is re-usable:

function usortarr(&$array, $key, $callback = 'strnatcasecmp') { uasort($array, function($a, $b) use($key, $callback) { return call_user_func($callback, $a[$key], $b[$key]); }); }  
 

For PHP 7 and later versions.

/**
* A method for sorting associative arrays by a key and a direction.
* Direction can be ASC or DESC.
*
* @param $array
* @param $key
* @param $direction
* @return mixed $array
*/

function sortAssociativeArrayByKey($array, $key, $direction){

switch ($direction){
case "ASC":
usort($array, function ($first, $second) use ($key) {
return $first[$key] <=> $second[$key];
});
break;
case "DESC":
usort($array, function ($first, $second) use ($key) {
return $second[$key] <=> $first[$key];
});
break;
default:
break;
}

return $array;
}

Usage:

$inventory = sortAssociativeArrayByKey($inventory, "price", "ASC");
 
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to sort an array of associative arrays by value of a given key in PHP?

 Programing Coderfunda     October 21, 2020     No comments   

 

How to sort an array of associative arrays by value of a given key in PHP?

 

11 years ago

Active 2 months ago
Viewed 484k times
470

Given this array:

$inventory = array(

   array("type"=>"fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),
   array("type"=>"pork", "price"=>5.43),

);

I would like to sort $inventory's elements by price to get:

$inventory = array(

   array("type"=>"pork", "price"=>5.43),
   array("type"=>"fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),

);

How can I do this?

 

19 Answers

638

You are right, the function you're looking for is array_multisort().

Here's an example taken straight from the manual and adapted to your case:

$price = array();
foreach ($inventory as $key => $row)
{
    $price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);

As of PHP 5.5.0 you can use array_column() instead of that foreach:

$price = array_column($inventory, 'price');

array_multisort($price, SORT_DESC, $inventory);

 

 Answer

42

Since your array elements are arrays themselves with string keys, your best bet is to define a custom comparison function. It's pretty quick and easy to do. Try this:

function invenDescSort($item1,$item2)
{
    if ($item1['price'] == $item2['price']) return 0;
    return ($item1['price'] < $item2['price']) ? 1 : -1;
}
usort($inventory,'invenDescSort');
print_r($inventory);

Produces the following:

Array
(
    [0] => Array
        (
            [type] => pork
            [price] => 5.43
        )

    [1] => Array
        (
            [type] => fruit
            [price] => 3.5
        )

    [2] => Array
        (
            [type] => milk
            [price] => 2.9
        )

)

 

Combining with some of the other comments here (uasort and inline anonymous functions), you get this one-liner: uasort( $inventory, function ($a, $b) { if ( $a==$b ) return 0; else return ($a > $b) ? -1 : 1; });

 

25

I ended on this:

function sort_array_of_array(&$array, $subfield)
{
    $sortarray = array();
    foreach ($array as $key => $row)
    {
        $sortarray[$key] = $row[$subfield];
    }

    array_multisort($sortarray, SORT_ASC, $array);
}

Just call the function, passing the array and the name of the field of the second level array. Like:

sort_array_of_array($inventory, 'price');
 
 

        
19

You can use usort with anonymous function, e.g.

usort($inventory, function ($a, $b) { return strnatcmp($a['price'], $b['price']); });
 
 

        
5

I use uasort like this

<?php
$users = [
    [
        'username' => 'joe',
        'age' => 11
    ],
    [
        'username' => 'rakoto',
        'age' => 21
    ],
    [
        'username' => 'rabe',
        'age' => 17
    ],
    [
        'username' => 'fy',
        'age' => 19
    ],    
];


uasort($users, function ($item, $compare) {
    return $item['username'] >= $compare['username']; 
});

var_dump($users);
 
        
3

This function is re-usable:

function usortarr(&$array, $key, $callback = 'strnatcasecmp') { uasort($array, function($a, $b) use($key, $callback) { return call_user_func($callback, $a[$key], $b[$key]); }); }  
 

For PHP 7 and later versions.

/**
 * A method for sorting associative arrays by a key and a direction.
 * Direction can be ASC or DESC.
 *
 * @param $array
 * @param $key
 * @param $direction
 * @return mixed $array
 */
function sortAssociativeArrayByKey($array, $key, $direction){

    switch ($direction){
        case "ASC":
            usort($array, function ($first, $second) use ($key) {
                return $first[$key] <=> $second[$key];
            });
            break;
        case "DESC":
            usort($array, function ($first, $second) use ($key) {
                return $second[$key] <=> $first[$key];
            });
            break;
        default:
            break;
    }

    return $array;
}

Usage:

$inventory = sortAssociativeArrayByKey($inventory, "price", "ASC");
 
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

PHPDoc type hinting for array of objects?

 Programing Coderfunda     October 21, 2020     hint, ide, php, phpdoc, var     No comments   

 

So, in PHPDoc one can specify @var above the member variable declaration to hint at its type. Then an IDE, for ex. PHPEd, will know what type of object it's working with and will be able to provide a code insight for that variable.

<?php
class Test
{
/** @var SomeObj */
private $someObjInstance;
}
?>

This works great until I need to do the same to an array of objects to be able to get a proper hint when I iterate through those objects later on.

So, is there a way to declare a PHPDoc tag to specify that the member variable is an array of SomeObjs? @var array is not enough, and @var array(SomeObj) doesn't seem to be valid, for example.

 

dd a comment

13 Answers

353

Use:

/* @var $objs Test[] */
foreach ($objs as $obj) {
// Typehinting will occur after typing $obj->
}

when typehinting inline variables, and

class A {
/** @var Test[] */
private $items;
}

for class properties.

Previous answer from '09 when PHPDoc (and IDEs like Zend Studio and Netbeans) didn't have that option:

The best you can do is say,

foreach ($Objs as $Obj)
{
/* @var $Obj Test */
// You should be able to get hinting after the preceding line if you type $Obj->
}

I do that a lot in Zend Studio. Don't know about other editors, but it ought to work.

 

895

In the PhpStorm IDE from JetBrains, you can use /** @var SomeObj[] */, e.g.:

/**
* @return SomeObj[]
*/

function getSomeObjects() {...}

The phpdoc documentation recommends this method:

specified containing a single type, the Type definition informs the reader of the type of each array element. Only one Type is then expected as element for a given array.

Example: @return int[]

 

25

PSR-5: PHPDoc proposes a form of Generics-style notation.

Syntax

Type[]
Type<Type>
Type<Type[, Type]...>
Type<Type[|Type]...>

Values in a Collection MAY even be another array and even another Collection.

Type<Type<Type>>
Type<Type<Type[, Type]...>>
Type<Type<Type[|Type]...>>

Examples

<?php

$x = [new Name()];
/* @var $x Name[] */

$y = new Collection([new Name()]);
/* @var $y Collection<Name> */

$a = new Collection();
$a[] = new Model_User();
$a->resetChanges();
$a[0]->name = "George";
$a->echoChanges();
/* @var $a Collection<Model_User> */

Note: If you are expecting an IDE to do code assist then it's another question about if the IDE supports PHPDoc Generic-style collections notation.

 

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

PHPDoc type hinting for array of objects?

 Programing Coderfunda     October 21, 2020     hint, ide, php, phpdoc, var     No comments   

 

So, in PHPDoc one can specify @var above the member variable declaration to hint at its type. Then an IDE, for ex. PHPEd, will know what type of object it's working with and will be able to provide a code insight for that variable.

<?php
  class Test
  {
    /** @var SomeObj */
    private $someObjInstance;
  }
?>

This works great until I need to do the same to an array of objects to be able to get a proper hint when I iterate through those objects later on.

So, is there a way to declare a PHPDoc tag to specify that the member variable is an array of SomeObjs? @var array is not enough, and @var array(SomeObj) doesn't seem to be valid, for example.

 

dd a comment

13 Answers

353

Use:

/* @var $objs Test[] */
foreach ($objs as $obj) {
    // Typehinting will occur after typing $obj->
}

when typehinting inline variables, and

class A {
    /** @var Test[] */
    private $items;
}

for class properties.

Previous answer from '09 when PHPDoc (and IDEs like Zend Studio and Netbeans) didn't have that option:

The best you can do is say,

foreach ($Objs as $Obj)
{
    /* @var $Obj Test */
    // You should be able to get hinting after the preceding line if you type $Obj->
}

I do that a lot in Zend Studio. Don't know about other editors, but it ought to work.

 

895

In the PhpStorm IDE from JetBrains, you can use /** @var SomeObj[] */, e.g.:

/**
 * @return SomeObj[]
 */
function getSomeObjects() {...}

The phpdoc documentation recommends this method:

specified containing a single type, the Type definition informs the reader of the type of each array element. Only one Type is then expected as element for a given array.

Example: @return int[]

 

25

PSR-5: PHPDoc proposes a form of Generics-style notation.

Syntax

Type[]
Type<Type>
Type<Type[, Type]...>
Type<Type[|Type]...>

Values in a Collection MAY even be another array and even another Collection.

Type<Type<Type>>
Type<Type<Type[, Type]...>>
Type<Type<Type[|Type]...>>

Examples

<?php

$x = [new Name()];
/* @var $x Name[] */

$y = new Collection([new Name()]);
/* @var $y Collection<Name> */

$a = new Collection(); 
$a[] = new Model_User(); 
$a->resetChanges(); 
$a[0]->name = "George"; 
$a->echoChanges();
/* @var $a Collection<Model_User> */

Note: If you are expecting an IDE to do code assist then it's another question about if the IDE supports PHPDoc Generic-style collections notation.

 

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

php 7.4 xampp Trying to access array offset on value of type null

 Programing Coderfunda     October 21, 2020     Laravel, php, php-7.4     No comments   

Php 7.4 xampp Trying to access array offset on value of type null

 I m working with lravel 7 project before i used to work with xampp 7.3.21 / PHP 7.3.21 and everything is so good ive upgraded to xampp 7.4.9 / PHP 7.4.9 and i get

Trying to access array offset on value of type null 

in the most of my porject and this is example

public function show
(
$id,
// selects
$selects_names,
$selects_languages,
$selects_models,
$selects_policies,
$selects_types,
$selects_ranks,
// end selects
)
{
return view('curd.show',compact
(
'id'
// select
'selects_names',
'selects_languages',
'selects_models',
'selects_policies',
'selects_types',
'selects_ranks',
// end selects
));
}

and this is the blade code

    @if($selects_names)
@foreach($selects_names as $key => $selects_name)
@include(
'treats.show_selects',
[
'name' => $selects_name,
'language' => $selects_languages[$key],
'model' => $selects_models[$key],
'policy' => $selects_policies[$key] ?? null,
'show_type' => $selects_types[$key],
'rank' => $selects_ranks[$key] ?? null,
]
)
@endforeach
@endif

and always get the above error most of my program is included from the code above they are treate function and now most of it now working

 

 

1 Answer

2

Some key in $select_names is probably not in the other arrays. Define a default value for the other arrays as you did for $select_policies and $select_ranks:

[
'name' => $selects_name,
'language' => $selects_languages[$key] ?? '',
'model' => $selects_models[$key] ?? null,
'policy' => $selects_policies[$key] ?? null,
'show_type' => $selects_types[$key] ?? null,
'rank' => $selects_ranks[$key] ?? null,
]

 

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

php 7.4 xampp Trying to access array offset on value of type null

 Programing Coderfunda     October 21, 2020     Laravel, php, php-7.4     No comments   

Php 7.4 xampp Trying to access array offset on value of type null

 I m working with lravel 7 project before i used to work with xampp 7.3.21 / PHP 7.3.21 and everything is so good ive upgraded to xampp 7.4.9 / PHP 7.4.9 and i get

Trying to access array offset on value of type null 

in the most of my porject and this is example

public function show
(
    $id,
    // selects
        $selects_names,
        $selects_languages,
        $selects_models,
        $selects_policies,
        $selects_types,
        $selects_ranks,
    // end selects
)
{
    return view('curd.show',compact
    (
        'id'
        // select
            'selects_names',
            'selects_languages',
            'selects_models',
            'selects_policies',
            'selects_types',
            'selects_ranks',
        // end selects
    ));
}

and this is the blade code

    @if($selects_names)
    @foreach($selects_names as $key => $selects_name)
        @include(
            'treats.show_selects',
            [
                'name' => $selects_name,
                'language' => $selects_languages[$key],
                'model' => $selects_models[$key],
                'policy' => $selects_policies[$key]  ?? null,
                'show_type' => $selects_types[$key],
                'rank' => $selects_ranks[$key] ?? null,
            ]
        )
    @endforeach
@endif

and always get the above error most of my program is included from the code above they are treate function and now most of it now working

 

 

1 Answer

2

Some key in $select_names is probably not in the other arrays. Define a default value for the other arrays as you did for $select_policies and $select_ranks:

[
    'name' => $selects_name,
    'language' => $selects_languages[$key] ?? '',
    'model' => $selects_models[$key] ?? null,
    'policy' => $selects_policies[$key]  ?? null,
    'show_type' => $selects_types[$key] ?? null,
    'rank' => $selects_ranks[$key] ?? null,
]

 

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Trying to access array offset on value of type null

 Programing Coderfunda     October 21, 2020     php, php-7.4     No comments   

 Trying to access array offset on value of type null

Migrating from php 7.1 to 7.4. We have like 500 functional tests for an API, and some of them started to fail with an error after the migration was complete. These tests were passing before everywhere, and now fail everywhere - not all, just 39.

Environment information:

  • php 7.4
  • codeception
  • yii2

Stack trace:

...\api\vendor\codeception\codeception\src\Codeception\Subscriber\ErrorHandler.php:83
...\api\tests\functional\SomeFileHereCest.php:72
...\api\vendor\codeception\codeception\src\Codeception\Lib\Di.php:127
...\api\vendor\codeception\codeception\src\Codeception\Test\Cest.php:138
...\api\vendor\codeception\codeception\src\Codeception\Test\Cest.php:97
...\api\vendor\codeception\codeception\src\Codeception\Test\Cest.php:80
...\api\vendor\codeception\codeception\src\Codeception\Test\Test.php:88
... more stuff here, not important

Since ErrorHandler.php:83 this is just catching the error, let's look at the SomeFileHereCest.php:72:

// declaration of the apiPrefix variable in the class.
protected $apiPrefix;
//...

public function _before(FunctionalTester $I)
{
$this->apiPrefix = $this->config['backend']['api_prefix']; // this is the line 72
//... more similar stuff later

So the $this->config['backend']['api_prefix'] this is a string("v1")

And I dont see where is the issue with this and how to dig into it deeper. Any ideas?

 

check isset($this->config), isset($this->config['backend']) and isset($this->config['backend']['api_prefix']) first

 

2 Answers

8

Sounds like your variable isn't set.

Check with the following isset calls:

isset($this->config); 
isset($this->config['backend']);
isset($this->config['backend']['api_prefix']);

You can actually check multiple vars in one isset call (isset($x, $y, $z)), but this will let you see which var specifically is missing

 

0

use (??) (double question mark operator) ("null coalescing operator") to avoid unset arrays.

this unit test is giving me "success"

class PhpTest extends TestCase
{
public function test_php_74()
{
//Trying to access array offset on value of type null

$this->assertSame('7.4.9', phpversion());

$a = null;
$this->assertTrue($a ?? true);
$this->assertTrue($a['a'] ?? true);
$this->assertTrue($a['a']['a'] ?? true);

$a = [];
$this->assertSame([], $a);
$this->assertTrue($a['a'] ?? true);
$this->assertTrue($a['a']['a'] ?? true);
}
}

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Trying to access array offset on value of type null

 Programing Coderfunda     October 21, 2020     php, php-7.4     No comments   

 Trying to access array offset on value of type null

Migrating from php 7.1 to 7.4. We have like 500 functional tests for an API, and some of them started to fail with an error after the migration was complete. These tests were passing before everywhere, and now fail everywhere - not all, just 39.

Environment information:

  • php 7.4
  • codeception
  • yii2

Stack trace:

...\api\vendor\codeception\codeception\src\Codeception\Subscriber\ErrorHandler.php:83
...\api\tests\functional\SomeFileHereCest.php:72
...\api\vendor\codeception\codeception\src\Codeception\Lib\Di.php:127
...\api\vendor\codeception\codeception\src\Codeception\Test\Cest.php:138
...\api\vendor\codeception\codeception\src\Codeception\Test\Cest.php:97
...\api\vendor\codeception\codeception\src\Codeception\Test\Cest.php:80
...\api\vendor\codeception\codeception\src\Codeception\Test\Test.php:88
... more stuff here, not important

Since ErrorHandler.php:83 this is just catching the error, let's look at the SomeFileHereCest.php:72:

// declaration of the apiPrefix variable in the class.
protected $apiPrefix;
//...

public function _before(FunctionalTester $I)
{
    $this->apiPrefix = $this->config['backend']['api_prefix']; // this is the line 72
    //... more similar stuff later

So the $this->config['backend']['api_prefix'] this is a string("v1")

And I dont see where is the issue with this and how to dig into it deeper. Any ideas?

 

check isset($this->config), isset($this->config['backend']) and isset($this->config['backend']['api_prefix']) first

 

2 Answers

8

Sounds like your variable isn't set.

Check with the following isset calls:

isset($this->config); 
isset($this->config['backend']);
isset($this->config['backend']['api_prefix']);

You can actually check multiple vars in one isset call (isset($x, $y, $z)), but this will let you see which var specifically is missing

 

0

use (??) (double question mark operator) ("null coalescing operator") to avoid unset arrays.

this unit test is giving me "success"

class PhpTest extends TestCase
{
    public function test_php_74()
    {
        //Trying to access array offset on value of type null

        $this->assertSame('7.4.9', phpversion());

        $a = null;
        $this->assertTrue($a ?? true);
        $this->assertTrue($a['a'] ?? true);
        $this->assertTrue($a['a']['a'] ?? true);

        $a = [];
        $this->assertSame([], $a);
        $this->assertTrue($a['a'] ?? true);
        $this->assertTrue($a['a']['a'] ?? true);
    }
}

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Message: Trying to access array offset on value of type null [duplicate]

 Programing Coderfunda     October 21, 2020     No comments   

Message: Trying to access array offset on value of type null [duplicate]

 

This question already has answers here:
Trying to access array offset on value of type null (2 answers)
Closed 10 months ago.

I'm getting this error on multiple occasion in a script (invoiceplane) I have been using for a few years now but which hasn't been maintained unfortunately by its creators:

Message: Trying to access array offset on value of type null

My server has been upgrade to PHP 7.4 and I'm looking for a way to fix the issues and maintain the script myself since I'm very happy with it.

This is what's on the line that gives the error:

$len = $cOTLdata['char_data'] === null ? 0 : count($cOTLdata['char_data']);

$cOTLdata is passed to the function:

public function trimOTLdata(&$cOTLdata, $Left = true, $Right = true)
{
$len = $cOTLdata['char_data'] === null ? 0 : count($cOTLdata['char_data']);
$nLeft = 0;
$nRight = 0;
//etc

It's included in mpdf btw, but simply overwriting the files from the github repository did not fix the errors.

 

 

1 Answer

39

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

 

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Message: Trying to access array offset on value of type null [duplicate]

 Programing Coderfunda     October 21, 2020     No comments   

Message: Trying to access array offset on value of type null [duplicate]

 

This question already has answers here:
Trying to access array offset on value of type null (2 answers)
Closed 10 months ago.

I'm getting this error on multiple occasion in a script (invoiceplane) I have been using for a few years now but which hasn't been maintained unfortunately by its creators:

Message: Trying to access array offset on value of type null

My server has been upgrade to PHP 7.4 and I'm looking for a way to fix the issues and maintain the script myself since I'm very happy with it.

This is what's on the line that gives the error:

$len = $cOTLdata['char_data'] === null ? 0 : count($cOTLdata['char_data']);

$cOTLdata is passed to the function:

public function trimOTLdata(&$cOTLdata, $Left = true, $Right = true)
{
    $len = $cOTLdata['char_data'] === null ? 0 : count($cOTLdata['char_data']);
    $nLeft = 0;
    $nRight = 0;
    //etc

It's included in mpdf btw, but simply overwriting the files from the github repository did not fix the errors.

 

 

1 Answer

39

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

 

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Older Posts Home

Meta

Popular Posts

  • Write API Integrations in Laravel and PHP Projects with Saloon
    Write API Integrations in Laravel and PHP Projects with Saloon Saloon  is a Laravel/PHP package that allows you to write your API integratio...
  • Credit card validation in laravel
      Validation rules for credit card using laravel-validation-rules/credit-card package in laravel Install package laravel-validation-rules/cr...
  • iOS 17 Force Screen Rotation not working on iPAD only
    I have followed all the links on Google and StackOverFlow, unfortunately, I could not find any reliable solution Specifically for iPad devic...
  • C++ in Hindi Introduction
    C ++ का परिचय C ++ एक ऑब्जेक्ट ओरिएंटेड प्रोग्रामिंग लैंग्वेज है। C ++ को Bjarne Stroustrup द्वारा विकसित किया गया था। C ++ में आने से पह...
  • Send message via CANBus
    After some years developing for mobile devices, I've started developing for embedded devices, and I'm finding a new problem now. Th...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

Loading...

Laravel News

Loading...

Copyright © CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda