Looking to get a count of particular key=>values in an multi dimensional array. What I have works i.e. the result is correct, but I can't seem to get rid of the Undefined Index notice.
$total_arr = array();
foreach($data['user'] as $ar) {
$total_arr[$ar['city']]++;
}
print_r($total_arr);
Any ideas? I have tried isset within the foreach loop, but no joy...
$total_arr = array();
foreach($data['user'] as $ar) {
if(array_key_exists($ar['city'],$total_arr) {
$total_arr[$ar['city']]++;
} else {
$total_arr[$ar['city']] = 1; // Or 0 if you would like to start from 0
}
}
print_r($total_arr);
PHP will throw that notice if your index hasn't been initialized before being manipulated. Either use the # symbol to suppress the notice or use isset() in conjunction with a block that will initialize the index value for you.
Related
In foreach loop, I am trying to add some additional property for the source array or objects. That gives me the following notice.
Notice: Undefined property: stdClass::$total
foreach ($this->products as $p_row) {
$this->data[ $p_row->group_id ][] = $p_row;
// getting index error here
$p_row->total += gs_get_product_qty_price($p_row->product, $p_row->qty);
}
However, if I add annotation # the error is gone.
foreach ($this->products as $p_row) {
$this->data[ $p_row->group_id ][] = $p_row;
// adding # the error gone
#$p_row->total += gs_get_product_qty_price($p_row->product, $p_row->qty);
}
As far as I understood is on the first iteration, it is not defined; maybe that is why showing an error.
Can anyone explain to me to clear my thought, and is it okay to use
# to avoid error?
The same notice occurs if I try to set data in
Notice: Undefined index: total
$this->data[$p_row->group_id]['total'] += gs_get_product_qty_price($p_row->product, $p_row->qty);
Is it the solution?
foreach ($this->products as $p_row) {
$p_row->total = 0;
$this->data[ $p_row->group_id ][] = $p_row;
$p_row->total += gs_get_product_qty_price($p_row->product, $p_row->qty);
}
I think in foreach loop you can't add an index, you have to create index before loop. # is just ignore Notices.
And in last your code, a "=" is extra.
since $this->data[$p_row->group_id]['total'] it is not defined first
and you are $this->data[$p_row->group_id]['total']+= adding value to
it it is throwing error. you can use this :
if(isset($this->data[$p_row->group_id]['total'])){
$this->data[$p_row->group_id]['total']+=gs_get_product_qty_price($p_row->product, $p_row->qty);
}else{
$this->data[$p_row->group_id]['total']= gs_get_product_qty_price($p_row->product, $p_row->qty);
}
Since $p_row->total doesn't exist yet, define it instead of trying to adding to it. Simply change += to =.
foreach ($this->products as $p_row) {
$this->data[ $p_row->group_id ][] = $p_row;
$p_row->total = gs_get_product_qty_price($p_row->product, $p_row->qty);
}
When you use +=, PHP will first read the initial value of the property and adds to that value. But since the property doesn't exist, it tries to read from an undefined property, which will throw the warning you see. Changing to = defines and sets the value instead.
I have two arrays object:
$seo_items = collect($resource->items)->values();
$api_items = collect($api_items)->values();
And, I want to iterate these elements and add the property size, which belongs to the $api_items array to the $seo_items array.
foreach($seo_items as &$seo_item)
{
foreach($api_items as $item)
{
if($item->article_id == $seo_item->article->article_erp_id)
{
$seo_item->article->size == $item->size;
$items_result[] = $seo_item;
}
}
}
The problem is that I can not assign this value, because php report this error:
Undefined property: stdClass::$size
How can I do this ?
Seems it is result of typing.
You have used == ( comparison operator), which is comparing with property which doesn't exist,instead of assigning the value.
$seo_item->article->size == $item->size;
changing it to
$seo_item->article->size = $item->size;
Should resolve your problem.
I have 2 arrays and i want to make a 3rd array after comparison of the 2 arrays. Code is as follows:
foreach($allrsltntcatg as $alltests)
{
foreach($alltests as $test)
{
foreach($allCatgs as $catg)
{
if($catg['testcategoryid'] == $test['testcategory_testcategoryid'])
{
$catcounts[$catg['testcategoryname']] +=1;
}
}
}
}
It, although returns the right answer, it also generates a PHP error and says undefined index and prints all errors and also the right answer.
I just want to avoid the array out of bound error. Kindly help me
Problem is in if condition correct like below : You have to initialize array first and than you can increment value
if($catg['testcategoryid'] == $test['testcategory_testcategoryid'])
{
if (isset($catcounts[$catg['testcategoryname']]))
$catcounts[$catg['testcategoryname']] +=1;
else
$catcounts[$catg['testcategoryname']] =1;
}
When the array try to add some arithmetic operation of undefined index such as $catg['testcategoryname'] in the $catcounts array then the warning generates. Before add the number you have to check the index is present or not, and of not then just assign value otherwise add into it.
So do it in this way just if condition-
if(....){
if(array_key_exists($catg['testcategoryname'], $catcounts))
$catcounts[$catg['testcategoryname']] +=1; // Add into it
else
$catcounts[$catg['testcategoryname']] = 1; // Assign only
}
More about array key exists--See more
$catg['testcategoryname'] should represent an index in $catcounts array.
I have a multidimensional array produced by json_decode(). The json is dynamically generated, that means some keys will be present randomly.
I would like to avoid Undefined index: notice, so i encapsulated the calls to the array in a function like this:
function exists($value) {
if (isset($value)) {
return $value;
}
}
I then call data:
$something = exists($json_array['foo']['bar']['baz']);
But i still get the Undefined index: baz notice. Any suggestions?
It seems you are new to PHP, so I'll give a bit lengthier answer than normal.
$something = exists($json_array['foo']['bar']['baz']);
This is equivalent to what you wrote:
$baz = $json_array['foo']['bar']['baz'];
$something = exists($baz);
As you may have noticed, this means that $json_array['foo']['bar']['baz'] is evaluated before it's passed to exists(). This is where the undefined index is coming from.
The correct idiom would be more like this:
$something = NULL;
if (isset($json_array['foo']['bar']['baz'])) {
$something = $json_array['foo']['bar']['baz'];
}
The following is also identical to the above lines:
$something = isset($json_array['foo']['bar']['baz'])
? $json_array['foo']['bar']['baz']
: NULL;
You would have to chain the exists calls one by one, because you are trying to dereference the array before you send it to the exists function.
See this question for more info: Check if a "run-time" multidimensional array key exists
$json_array['foo']['bar']['baz'] fails when you pass it as an argument, before it's passed to isset(). That is your problem.
If accessing an undefined index of a null reference, PHP does not throw any errors.
<?php
$array = &$foo['bar'];
if ($array['stuff']) echo 'Cool'; // No PHP notice
$array['thing'] = 1; // Array created; $foo['bar']['thing'] == 1
$array['stuff']; // PHP notice
If $array wasn't a reference PHP would have complained on the first line.
Why doesn't it for references? Do I need bother with isset for null references, or is PHP complaining internally and not letting me know?
In your code $array is null. The following code will not give you a notice either:
$b = null;
if ($b['stuff']) echo 'cool';
This is strange, this comment in the documentation points to that fact.
You must raise your error reporting level. Your example $array['stuff'] will throw warnings about index not found. I often combine a test for key in with the evaluation so as to prevent those warnings:
if( array_key_exists("blah",$arr) && strlen($arr['blah']) > 0 ) {
; // do stuff here
}
I often combine variables in with array names because anytime I have to cut-n-paste copy code to the next section to do the same-ish thing, I'd rather make an array of variable names and then iterate through the variable names. The most absurd condition is when I have billing and shipping data to manipulate, where I'll have an array variable name $BorS or just $BS and then at the top, set $BorS="shipping"; and end up with really interesting statements like:
${$BorS."data"}[${$BorS."_addr1"}]=$input_array[$BorS."_address_line_1"];
Why not just do:
$array = array();