Php 7 "cannot use string offset as an array" - php

We've recently upgraded to Php 7.4 and are encountering a potential fatal error alert for the following code block:
$total = 0;
$balance = 0;
if (is_array($company['history']) && ($histCount = count($company['history']))) {
for ($i = $histCount - 1; $i >= 0; $i--) {
$total += $company['history'][$i]['amt_total'];
$balance += $company['history'][$i]['due'];
$company['history'][ $i ]['balance'] = $balance; // EA flags as potential fatal error
$company['history'][ $i ]['total'] = $total; // EA flags as potential fatal error
}
}
Each history element in the $company has (among others) amt_total, due, balance, and total initialized, with the last two being initialized to 0.
EA flags the two lines indicated, saying "Could provoke a PHP Fatal error (cannot use string offset as an array)."
Grateful to anyone who can help me understand what's wrong here.
ADDITIONAL INFO
Someone asked where the code for defining $company comes from...
foreach ($this->orderList as $order) {
if ($order['amt_paid'] !== $order['real_amt_paid'] && !empty($order['real_amt_paid'])) {
$order['amt_paid'] = $order['real_amt_paid'];
}
$row = [];
foreach ($this->customerHistoryColumns as $col) {
$order[$col[0]] = ($order[$col[0]] === null ? "" : str_replace("&", "&", $order[$col[0]]));
switch ($col[0]) {
...
case "due":
$row['due'] = $order['amt_total'] - $order['amt_paid'];
break;
...
default:
$row[$col[0]] = $order[$col[0]];
break;
}
}
$row['balance'] = 0;
$row['total'] = 0;
$arr['history'][] = $row;
}
return $arr['history'];
The company itself is defined elsewhere; this is simply retrieving the history element.
FWIW, the code has worked flawlessly for years; it's the upgrade to Php7 that has raised this issue.

Related

Laravel Trying to Get property of non object (from eloquent model)

Already read some of questions about this problem on stackoverflow and none of that answers apply to me.
When I run:
$item_price = ItemPrice::where('item_name',$itemname)->first();
and then
$item_price->price
I get Trying to get property of non-object but when I run:
dd($item_price = ItemPrice::where('item_name',$itemname)->first());
It's returning object with attributes name, price etc. I don't really understand what is happening here.
Full code:
foreach ($inventorydecoded->assets as $asset) {
$i = 0;
$a = 0;
while ($a < 1) {
if ($inventorydecoded->descriptions[$i]->classid == $asset->classid) {
$a = 1;
$classid = $inventorydecoded->descriptions[$i]->classid;
$itemname = $inventorydecoded->descriptions[$i]->market_hash_name;
$tradable = $inventorydecoded->descriptions[$i]->tradable;
$name_color = $inventorydecoded->descriptions[$i]->name_color;
;
}
$i++;
} // end of while
if ($tradable === 1 && strpos_arr($itemname, $blacklist) == false ) {
$item_price = ItemPrice::whereItemName($itemname)->first();
// dd(ItemPrice::where('item_name',$itemname)->first());
$items[] = ['assetid' => $asset->assetid,'classid'=> $classid,'itemname'=>$itemname,'name_color'=>$name_color,'price'=> $item_price->price];
$serialized_inventory = serialize($items);
}
} // end of foreach
You're using this query in loop, so one of those is empty and returns null. So you need to do simple check:
if (is_null($item_price)) {
// There is no price for this item, do something.
}
Try this:
$item_price = ItemPrice::whereItemName($itemname)->first();

PHP Fatal Error Cannot Use String Offset As Array

I keep getting a fatal error when a script is ran on my php server,
This web app was built ten years ago and I am currently clearing errors so we can start updating it. Current version PHP 5.2.17
Fatal error: Cannot use string offset as an array in /home/user/public_html/admin/script.php on line 1418
This is the line the error is on,
$name = $d["#"]["_Name"];
This is the full function,
if (isset($b["_BORROWER"]["EMPLOYER"])) {
if (!isset($b["_BORROWER"]["EMPLOYER"][0])) {
$temp = $b["_BORROWER"]["EMPLOYER"];
unset($b["_BORROWER"]["EMPLOYER"]);
$b["_BORROWER"]["EMPLOYER"][0] = $temp;
}
foreach($b["_BORROWER"]["EMPLOYER"] as $c => $d) {
$pid = '0';
// Finish up.
$item["type"] = "Personal";
$name = $d["#"]["_Name"];
//check for files in other bureaus
$query = doquery("SELECT name,id FROM <<myitems>> WHERE cid='".$client["id"]."' AND type='Personal'");
$results = dorow($query);
if($results){
if(isset($results['name'])){
$temp = $results;
unset($results);
$results[0] = array($temp);
}
foreach($results as $c){
if(isset($c['name'])){
if($address == decrypt_string($c['name'])) {
$pid = $c['id'];
break;
};
}
}
}
Does anyone understand what is triggering this error and how to fix it?
You can use isset() to check the array value exists or not like,
$name = isset($d["#"]["_Name"]) ? $d["#"]["_Name"] : "";

debug_backtrace - long parameter

I have the following function:
function backtrace($Object=false)
{
$x = 0;
foreach((array)debug_backtrace($Object) as $aVal)
{
$row[$x]['file'] = $aVal['file'];
$row[$x]['line'] = $aVal['line'];
$row[$x]['function'] = $aVal['function'];
$row[$x]['class'] = $aVal['class'];
$row[$x]['args'] = $aVal['args'];
++$x;
}
return $row;
}
But when I use it, I'm getting an error like below:
Warning: debug_backtrace() expects parameter 1 to be long, string given in /mypath/ on line 717 ---> foreach((array)debug_backtrace($Object) as $aVal)
What's causing the error? How can I fix it?
The first parameter of debug_backtrace() is a bitmask of options (i.e. a long). It is a simple boolean true/false in PHP versions prior to 5.3.6.
To fix it, either don't pass in the $Object variable you're currently passing in or update it to be any combination of the supported options that you want to be used.
Example:
$Object = DEBUG_BACKTRACE_IGNORE_ARGS | DEBUG_BACKTRACE_PROVIDE_OBJECT;
If you want to add a pre-condition to your current block of code that will set a default value if $Object is invalid, you could try something like:
function backtrace($Object = false) {
if (!is_long($Object) || (!($Object & DEBUG_BACKTRACE_PROVIDE_OBJECT) && !($Object & DEBUG_BACKTRACE_IGNORE_ARGS))) {
$Object = 0;
}
$x = 0;
foreach((array)debug_backtrace($Object) as $aVal) {
$row[$x]['file'] = $aVal['file'];
$row[$x]['line'] = $aVal['line'];
$row[$x]['function'] = $aVal['function'];
$row[$x]['class'] = $aVal['class'];
$row[$x]['args'] = $aVal['args'];
++$x;
}
return $row;
}
for php >= 5.3.6, you should use bitmask options
function backtrace($Object=false) {
$x = 0;
foreach((array)debug_backtrace($Object ? DEBUG_BACKTRACE_PROVIDE_OBJECT : 0) as $aVal)
{
$row[$x]['file'] = $aVal['file'];
$row[$x]['line'] = $aVal['line'];
$row[$x]['function'] = $aVal['function'];
$row[$x]['class'] = $aVal['class'];
$row[$x]['args'] = $aVal['args'];
++$x;
}
return $row;
}

Fatal error: Cannot use string offset as an array Not making any sense at all

I have the fatal error coming up in the error log but it is not affecting the application at all for some reason. This is the code that is running and it makes no sense why it generating the PHP error.
for ($i = 1; $i <= $tournament['num_score_fields']; $i++) {
$scoresArrayTemp = array(
'score',
'dist',
'dateShot',
'tens',
'nines'
);
foreach($scoresArrayTemp AS $val){
if(empty($scores[$i][$val])){
$scores[$i][$val] = '';
}
}
}
The error is generated by this line
$scores[$i][$val] = '';
Any help would be greatly appreciated thanks!
Based on answer 1 I changed code to this:
for ($i = 1; $i <= $tournament['num_score_fields']; $i++) {
$scoresArrayTemp = array(
'score'=>'',
'dist'=>'',
'dateShot'=>'',
'tens'=>'',
'nines'=>''
);
if(!is_array($scores[$i])){
$scores[$i] = $scoresArrayTemp;
}
echo $scores[$i]['score'];
}
Still gets the error on the last line when echoing out the variable
$scores[$i] is not an array, so PHP is preventing you from assigning a value to the index at $val. You probably want this:
if(is_array($scores[$i]) && empty($scores[$i][$val])){
$scores[$i][$val] = '';
}
i made some alteration in your code to check where the problem was:
<?php
$tournament['num_score_fields'] = 10;
for ($i = 1; $i <= $tournament['num_score_fields']; $i++) {
$scoresArrayTemp = array(
'score',
'dist',
'dateShot',
'tens',
'nines'
);
foreach($scoresArrayTemp AS $val){
if(empty($scores[$i][$val])){
$scores[$i][$val] = '';
echo 'a';
}
}
}
?>
and the output was :
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
dude there is no error out here.. it could be due to any other reason. check the code from top to bottom again or show what exact error is coming.

PHP multiplication weird behavior

I don't know if I have suffered some brain or sight damage, but I can't understand behavior of this code:
$po=1;
$po2=0;
echo $po.'*'.$po2.'=';
if($po*$po2) $po=1;
echo $po;
I'd expect the output to be 1*0=0, but actually it's 1*0=1.
$po is always 1. You initialize it to 1, and later in your if case, you have no else. So it remains 1.
Instead, add an `else:
$po = 1;
$po2 = 0;
echo $po.'*'.$po2.'=';
if ($po * $po2) {
// Unnecessary - it's already 1
$po = 1;
}
// Set it to 0...
else {
$po = 0;
}
echo $po;

Categories