php array's making the Undefined index: 0 notice go away - php

Right so i have E_NOTICES on and my code works its just i keep getting "Severity: Notice Message: Undefined index: 0" everytime i try to insert my data into the array with the set key. Its really annoying when ur trying to debug.
What am i doing wrong that will make the notices go away without turning off E_NOTICES?
foreach ($bracketmatches->result() as $row)
{
if(!isset($bracketdata[$row->position]))
{
$bracketdata[$row->position] = array();
}
$bracketdata[$row->position] = array("home_name" => $teams[$row->home_id]['team_name']);
}

Is $teams[$row->home_id] definitely defined?
edit: Quick and dirty test for you:
foreach ($bracketmatches->result() as $row)
{
if(!isset($teams[$row->home_id]))
{
die('GOTCHA!!!');
}
$bracketdata[$row->position] = array("home_name" => $teams[$row->home_id]['team_name']);
}

Impossible to say for certain without more information, but I would check that $row->position is set and that $row->home_id is set if there is any possibility they may be undefined.

You must initialize the base array before pushing values to it. The isset here doesn't really do anything. Just throw it away. If you still get the error make sure $teams[$row->home_id]['team_name'] is always set.
$bracketdata = array();
foreach ($bracketmatches->result() as $row)
{
$bracketdata[$row->position] = array("home_name" => $teams[$row->home_id]['team_name']);
}

$bracketdata = array();
foreach ($bracketmatches->result() as $row)
{
if (isset($row->position) && !empty($row->position) && isset($teams[$row->home_id]['team_name']))
$bracketdata[$row->position] = array("home_name" => $teams[$row->home_id]['team_name']);
}

Related

How to store specific JSON data in PHP and get rid of Undefined Index Notice?

I'm developing an app using PHP and I'm fetching data via api endpoint. I was able to get the data I want - a huge chunk of it, found here: https://gist.github.com/kamaelxiii/18ef0c1600330b98717b96db00532d6a
Now my blocker is I just want to get and store the specific ID of a player (look for name : kamaelxiii) my code was able to get the ID but the page also displays this message:
Notice: Undefined index: name in C:\xampp\htdocs\vgapp\index.php on line 230
I'm thinking that this is because I'm looping to the entire included block but not all contains the index name in it. I've tried adding break inside the for loop below but the ID that I'm after is not always the first in the list so there are times that the message above still shows - most of the time.
Here's my line of code that gets the specific ID:
if(is_array($finaljson) || is_object($finaljson)){
foreach ($finaljson['included'] as $key => $value) {
if($value['attributes']['name'] === $username){
$userid = $value['id'];
}
}
If you want to get rid of Notice, Then just use empty() or isset() in your foreach loop's if condition. below is the code.
if(is_array($finaljson) || is_object($finaljson)){
foreach ($finaljson['included'] as $key => $value) {
//you can use empty check
if(!empty($value['attributes']['name']) && $value['attributes']['name'] === $username){
$userid = $value['id'];
}
//or you can use isset
if(isset($value['attributes']['name']) && $value['attributes']['name'] === $username){
$userid = $value['id'];
}
}
It is not a serious problem.
error_reporting(0);
OR:
if(#$value['attributes']['name'] === $username){
$userid = $value['id'];
}

Passing variable variables into if statement - php

I have a series of variables in php:
move1A = $row['column'];
move2A = $row['column'];
move3A = $row['column'];
etc.
I want to create a variable that will represent these variables and check if it is NULL. I have spent quite a bit of time looking, and although I believe that variable variables may be the key to my problem. So far I have tried:
$current_move_check = 'move'.$moveCounter.'A';
and
$current_move_check = '$move'.$moveCounter.'A';
Neither seem to work. Any suggestions for making something like this work? Thanks!
UPDATE:
So I'm trying to loop the moveXA variables based on user input and I need to run different script whether it is null or set.
I thought that:
elseif (!$$current_move_check) {
and
elseif ($$current_move_check) {
would work but they seem to not be outputting as expected.
Considering your update, I'd really suggest you to use an array, rather than the variable variables trick. Your code would makes more sense and be easier to maintain :
$count = 0;
$moveA[++$count] = $row['column'];
$moveA[++$count] = $row[...];
$moveA[++$count] = $row[...];
...
foreach ($moveA as $key => $value) {
if ($value) { // = $$current_move_check
} else { // = !$$current_move_check
}
}
As #MatsLindh pointed out in its comment : "Variable variables are never a good idea. Unless you know when it makes sense to break that rule, don't."
$current_move_check = 'move'.$moveCounter.'A';
echo $$current_move_check;
now you can check this as well like
if($$current_move_check!=NULL)
{
// do your code
}

Undefined Index in php array

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.

declare an empty array of size 100 in codeigniter php

I am developing an application in php using codeigniter for a workflow process.
Now i need to declare an empty array of size 100 or 200 with null value default..whenever workflow executed anyways values get stored in to that array dynamically..
I am having a array in my view like
if(isset($value)){
foreach ($value as $row) {
$wer[] = $row;
}
}
Now whenever workflow runs automatically values get stored in view using form_dropdown('perfpmself_1',$rate,$wer[0],'class="self"');
from the above format i use to load all values from $wer[0] to $wer[50]. All values will displayed properly...but if there is no values in database to load it to an array..it is throwing an error like
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: wer
Filename: views/performancepm.php
Can anyone suggests a solution for this to overcome this error on my view screen??
Please help..thanks in advance
You didn't initialize $wer before trying to assign a value to it:
if(isset($value)){
$wer = array();
foreach ($value as $row) {
$wer[] = $row;
}
}
Try:
$options = array_fill_keys(range(0,99),null);
echo form_dropdown('perfpmself_1', $options);
Just define wer globally. Also I'd use array_push, but thats just me. Keep it simple:
$wer = array();
if(isset($value)){
foreach ($value as $row) {
array_push($wer, $row);
}
}
if(empty($wer)){
//wer has values
}else{
// wer is not empty
}
In regards to your comments, as far as I know there is only one way to enforce the required field specifically in the codeIgniter framework:
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
From the CodeIgniter Guide
Otherwise youll have to enforce it using JavaScript or in your own PHP code to see if is an empty field:
if (isset($_GET['username'])){
//username isnt blank
}else{
//username is blank
}

cleanest way to skip a foreach if array is empty [duplicate]

This question already has answers here:
Invalid argument supplied for foreach()
(20 answers)
Closed 7 years ago.
Not a major problem but I was wondering if there is a cleaner way to do this. It would be good to avoid nesting my code with an unnecessary if statement. If $items is empty php throws an error.
$items = array('a','b','c');
if(!empty($items)) { // <-Remove this if statement
foreach($items as $item) {
print $item;
}
}
I could probably just use the '#' error suppressor, but that would be a bit hacky.
There are a million ways to do this.
The first one would be to go ahead and run the array through foreach anyway, assuming you do have an array.
In other cases this is what you might need:
foreach ((array) $items as $item) {
print $item;
}
Note: to all the people complaining about typecast, please note that the OP asked cleanest way to skip a foreach if array is empty (emphasis is mine). A value of true, false, numbers or strings is not considered empty.
In addition, this would work with objects implementing \Traversable, whereas is_array wouldn't work.
The best way is to initialize every bloody variable before use.
It will not only solve this silly "problem" but also save you a ton of real headaches.
So, introducing $items as $items = array(); is what you really wanted.
$items = array('a','b','c');
if(is_array($items)) {
foreach($items as $item) {
print $item;
}
}
If variable you need could be boolean false - eg. when no records are returned from database or array - when records are returned, you can do following:
foreach (($result ? $result : array()) as $item)
echo $item;
Approach with cast((Array)$result) produces an array of count 1 when variable is boolean false which isn't what you probably want.
I wouldn't recommend suppressing the warning output. I would, however, recommend using is_array instead of !empty. If $items happens to be a nonzero scalar, then the foreach will still error out if you use !empty.
I think the best approach here is to plan your code so that $items is always an array. The easiest solution is to initialize it at the top of your code with $items=array(). This way it will represent empty array even if you don't assign any value to it.
All other solutions are quite dirty hacks to me.
foreach((array)$items as $item) {}
i've got the following function in my "standard library"
/// Convert argument to an array.
function a($a = null) {
if(is_null($a))
return array();
if(is_array($a))
return $a;
if(is_object($a))
return (array) $a;
return $_ = func_get_args();
}
Basically, this does nothing with arrays/objects and convert other types to arrays. This is extremely handy to use with foreach statements and array functions
foreach(a($whatever) as $item)....
$foo = array_map(a($array_or_string)....
etc
Ternary logic gets it down to one line with no errors. This solves the issue of improperly cast variables and undefined variables.
foreach (is_array($Items) || is_object($Items) ? $Items : array() as $Item) {
It is a bit of a pain to write, but is the safest way to handle it.
You can check whether $items is actually an array and whether it contains any items:
if(is_array($items) && count($items) > 0)
{
foreach($items as $item) { }
}
Best practice is to define variable as an array at the very top of your code.
foreach((array)$myArr as $oneItem) { .. }
will also work but you will duplicate this (array) conversion everytime you need to loop through the array.
since it's important not to duplicate even a word of your code, you do better to define it as an empty array at top.

Categories