Jump to content

scalar value error


StevenOliver

Recommended Posts

In this array, I have 3 broken tools at $10.00 each:

[TOOLS] => Array
   (
     [good_quality] => 3
     [good_price] => 10.00
     [broken] => 3
     [broken_price] => 5.00
   )
)

foreach($tools as $i => $val) {
echo 'We have '.$val["broken"].' broken tools at '.$val["broken_price"].' each";
}

Sometimes I have no broken tools, then the array will look like this:

[TOOLS] => Array
        (
            [good_quality] => 3
            [good_price] => 10.00
        )

)

If I were to run the loop now, it would give an "undefined index" error.

However, when I define the index like this, it will give a "Cannot use a scalar value as an array" error:

foreach($tools as $i => $val) {
if(!isset($val["broken"])) { $val["broken"] = 0; }
echo 'We have '.$val["broken"].' broken tools at '.$val["broken_price"].' each";
}

Why? And what is the best way to handle this, please?

Edited by StevenOliver
Link to comment
Share on other sites

You are running that loop with the index values already represented as $i .  Why do you want to mention an explicit index value?

foreach($tools as $i => $val) 
{
	if ($i == 'broken')
		echo "We have $val $i tools at {$val['broken_price']} each";
	if ($i == 'good_quality')
		echo "We have $val $i tools at {$val{'good_price']} each";
}

 

Link to comment
Share on other sites

$tools is not a collection of tools. It is an associative array containing 2 or 4 values. foreaching over an associative array is almost always incorrect.

if (isset($tools["good_quality"])) {
	printf("We have %s good quality tools at $%.02f each", $tools["good_quality"], $tools["good_price"]);
}
if (isset($tools["broken"])) {
	printf("We have %s broken tools at $%.02f each", $tools["broken"], $tools["broken_price"]);
}

 

Link to comment
Share on other sites

Might I suggest

$tools = [   'good'   => [ 'qty' => 3, 'price' => 10.00 ],
             'broken' => [ 'qty' => 3, 'price' => 5.00 ]
         ];
         
foreach ($tools as $condition => $data) {
    printf("We have %d %s tools at \$%0.2f each<br>", $data['qty'], $condition, $data['price']);
}

Gives

We have 3 good tools at $10.00 each
We have 3 broken tools at $5.00 each

 

Link to comment
Share on other sites

edit: pretty much repeating what they ^^^ said -

your data is not stored/indexed in a way that you can simply produce the desired output from it. also, 'tools' is a type/category of items.

assuming that wherever this data is retrieved from, you are only getting the data that you want in the order that you want it, or that you would filter the data before using it, see the following -

$items['tools']['good']['quantity'] = 3;
$items['tools']['good']['price'] = 10.00;
$items['tools']['broken']['quantity'] = 3;
$items['tools']['broken']['price'] = 5.00;

$curency = '$';

foreach($items as $type=>$arr)
{
	foreach($arr as $condition=>$item)
	{
		$price = number_format($item['price'],2);
		echo "We have {$item['quantity']} $condition $type at $curency$price each.<br>";
	}
}

 

Edited by mac_gyver
Link to comment
Share on other sites

Thank you all for your reply!

Ginerjm, I'm provided an array that sometimes has "broken tools" and sometimes does not. I wanted to have just one "blanket response" to echo whether the array has Broken Tools or  not (e.g.  if absent, then "you have 0 broken tools").

Requinix, good point. The fact that I missed this shows I'm lacking a fundamental understanding about arrays. Often when I'm coding I'll realize I don't really know what I'm doing, and then I'll take an hour (usually several hours or a day or more) to read up and learn. Nowadays I'm realizing that if I just go for the "quick fix" I'll never really know what I'm doing haha

Barand, Thank you -- as always, your coding is SO efficient clean and simple! As soon as I've corrected my mistake in my old code (and thus proven to myself I understand what I did wrong), I'll implement your code!

Mac_Gyver, your code definitely cleans up my code. However, I want to echo a "blanket statement" saying there are no "Broken Tools" if the array I'm provided makes no mention of Broken Tools. Your code says "$items['tools']['broken']['quantity'] = 3" but sometimes the array I'm provided does not have "broken" in it. I'm trying to "initialize" the $items['tools']['broken']['quantity'] at zero '0' if $items['tools']['broken']['quantity'] does not exist to begin with.

.... of course I could always do an "if Broken is not in the array at all" echo Blanket Statement One, otherwise echo Blanket Statement Two.... but that would be the quick fix and easy way out, and I wouldn't have learned anything :-)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.