Home > Back-end >  How to update the value inside the array?
How to update the value inside the array?

Time:07-08

I am using PHP , i have one array i am updating the value inside the array based on some conditions it's coming inside the if blocks but the value is not updating,can you give suggestions did i miss anything ..?

dump of $data['bookslist']

Array
(
    [0] => Array
        (
            [id] => 22
            [book_name] => tank1
            [book_type] => 1
            [status] => 1
        )

    [1] => Array
        (
            [id] => 23
            [book_name] => g1
            [book_type] => 2
            [status] => 1
        )
)

code

foreach($data['bookslist'] as $value){
            if(array_key_exists('book_type',$value)){

                if($value['book_type'] == '1'){
                    $data['bookslist'][$value]['book_type'] = 'Horror';
                    break;
                }
                if($value['book_type'] == '2'){
                    $value['book_type'][$value]['book_type']= 'Comedy';
                    break;
                }
                
            }
        }

CodePudding user response:

you use $value as the key but it is an array. By using pass-by-reference you can modify the array. Assumption:- you want to modify $data['booklist']. suggestion: you can also use a switch case if have a limited book_type.

foreach($data['bookslist'] as &$value){
        if(array_key_exists('book_type',$value)){

            if($value['book_type'] == '1'){
                $value['book_type'] = 'Horror';
                break;
            }
            if($value['book_type'] == '2'){
                $value['book_type']= 'Comedy';
                break;
            }
            
        }
    }

CodePudding user response:

You can use the key of your array :

foreach($data['bookslist'] as $k => $value){
    if(array_key_exists('book_type',$value)){
        if($value['book_type'] == '1'){
            $value['book_type'] = 'Horror';
        }
        if($value['book_type'] == '2'){
            $value['book_type'] = 'Comedy';
        }
        $data['bookslist'][$k] = $value;
        continue; //break will stop the foreach;
    }
}

But, do you mean "break" or "continue" ? If break, you stop the foreach loop with the first array which have the good condition. In your dump, only tank1 will have the update.

  • Related