explode() offset and delimiter warnings when delimiter is valid - php

I'm having a heck of a time trying to figure out what is going on. I have a block of code that is throwing some errors. Outside of the Warnings and Notices the code works fine and the arrays are not empty. But why I am getting those warnings and notices is bothersome. In my test environment I don't get the errors however when put on a different server they pop right up. I am stumped as to why. The lines of code that are throwing the errors and the errors being thrown are as follows
$libTitle = explode($libYearRes[0], $value);
Notice: Undefined offset: 0
Warning: explode(): Empty delimiter
$sortLibYearRes = explode(' ', $libYearRes[0]);
Notice: Undefined offset: 0
$libMovieRes = $sortLibYearRes[1];
Notice: Undefined offset: 1
The entire block of code is as follows with the problem lines denoted with a # in them
function checkMovieLibrary($movieTitle,$movieLibrary){
foreach ($movieLibrary as $value) {
preg_match('/\(\d\d\d\d\)\s\d\d\d*[Pp]/', $value, $libYearRes);
$libTitle = #explode($libYearRes[0], $value);
$libMovieTitle = rtrim($libTitle[0]);
$sortLibYearRes = #explode(' ', $libYearRes[0]);
//list($libMovieYear,$libMovieRes) = explode(' ', $libYearRes[0], 2);
$libMovieYear = $sortLibYearRes[0];
$libMovieRes = #$sortLibYearRes[1];
preg_match('/\(\d\d\d\d\)\s\d\d\d*[Pp]/', $movieTitle, $newfileYearRes);
$newFileTitle_array = explode($newfileYearRes[0], $movieTitle);
$newFileTitle = rtrim($newFileTitle_array[0]);
$sortFileYearRes = explode(' ', $newfileYearRes[0]);
$newFileMovieYear = $sortFileYearRes[0];
$newFileMovieRes = $sortFileYearRes[1];
if(stripos($libMovieTitle.' '.$libMovieYear, $newFileTitle.' '.$newFileMovieYear) !== false){
$moviesList_array[] = array('OriginalFile' => $value, 'NewFile' => $movieTitle);
return($moviesList_array);
}
}
return false;
}
//$movieTitle = "10 Cloverfield Lane (2016) 1080p.mkv"; //This is an example of $movieTitle string
//$movieLibrary = array('10 Cloverfield Lane (2016) 1080p.mkv','The Goonies (1985) 1080p.mp4'); this is an example of the $movieLibrary array
$doesMovieExist = checkMovieLibrary($Movie,$movieLibrary);
if(is_array($doesMovieExist) && $doesMovieExist !== false){
foreach($doesMovieExist as $fileKey => $fileValue) {
$originalFile = $fileValue['OriginalFile'];
$newFile = $fileValue['NewFile'];
}
//do some stuff here
}

First of all dont use # because it will bypass the error message. So user error_reporting(E_ALL) till development phase.
Then you are getting undefined offset it means your array is empty of does not exist so put a condition to check if it exist then the explode should work. It must be like that :
if(!empty($libYearRes[0]) || isset($libYearRes[0])) {
$libTitle = #explode($libYearRes[0], $value);
}

Undefined offset error means you're referring an array key that does not exist. If you like to see the array before processing it, use variable dump (var_dump) then you will see these array keys are not available for the given scenario.
you can avoid this error by checking array key really exist or not by using isset function. as example
if(isset($libYearRes[0])){ // will be true only if $libYearRes[0] is exist
$libTitle = explode($libYearRes[0], $value);
}

Related

PHP foreach over an array twice results in some warnings undefined index

I have the following php code that is looking for the last entry of test entry in a mysql query result.
It checks if the last entry is valid for a device or it tries to search the latest one in the for that type of test (or failing that leave it as untested). After that, it does the same for the second device in the same manner. However I get errors pointing to lines on second foreach loop.
if ($device1_valid) {
$Results_d1 = $History[$TestNo][$iter]['Results_d1'];
$Colour_d1 = Colour($Results_d1);
$Date_d1 = $History[$TestNo][$iter]['Date_'];
} else {
foreach ($History[$TestNo]['iter'] as $item) {
$device1_valid = $History[$TestNo][$item]['d1_valid'];
if ($sf1_valid) {
$Results_d1 = $History[$TestNo][$item]['Results_d1'];
$Colour_d1 = Colour($Results_d1);
$Date_d1 = $History[$TestNo][$item]['Date_'];
break;
} else {
$Results_d1 = "----";
$DateTime_d1 ="----";
$Colour_d1 = 'white';
}
}
}
unset($item);
if ($device2_valid) {
$Results_d2 = $History[$TestNo][$iter]['Results_d2'];
$Colour_d2 = Colour($Results_d2);
$Results_d2 = $History[$TestNo][$iter]['Results_d2'];
$Date_d2 = $History[$TestNo][$iter]['Date_'];
} else {
foreach ($History[$TestNo]['EntryNo'] as $item) {
$device2_valid = $History[$TestNo][$item]['d2_valid'];
if ($device2_valid) {
$Results_d2 = $History[$TestNo][$item]['Results_d2'];
$Colour_d2 = Colour($Results_d2);
$Date_d2 = $History[$TestNo][$item]['Date_'];
break;
} else {
$Results_d2 = "----";
$DateTime_d2 ="----";
$Colour_d2 = 'white';
}
}
This results in warnings for the second loop as such:
Notice: Undefined index: EntryNo in /server/filename.php on line 129
Warning: Invalid argument supplied for foreach() in /server/filename.php on line 129
Why is this error occurring and how will I be able to remove it? The query does result in correct data (which is displayed later but I don't understand why theses notifications and warning are happening. This only happens in the second foreach loop and not the first.
Edit:
$History[$TestNo] is a multidimensional array.... so vardump gives array(49) { [0]=> array(25) {....} [1]=> array(25) [2]=> array(25){...} etc. I call this function setting $EntryNo to 0.
vardump $History[$TestNo][$EntryNo] simply gives array(25) {....}
There are no warnings in the first loop but second loop it says the index is undefined. This is key reason why the other question identified as duplicate does not address my issue. The question is why is this occuring in the second foreach loop and how can I avoid this.
For
`Notice: Undefined index: EntryNo in /server/filename.php on line 129
Warning: Invalid argument supplied for foreach() in /server/filename.php on line 129'
It must be like this at foreach($History[$TestNo]['EntryNo'] as $item) There is no element in array $History[$TestNo] with with key EntryNo.
Would you please var_dump($History[$TestNo]) and check it ?
Notice: Undefined variable: Colour_sf2 in /server/filename.php on line 184
For this, You have not included enough code here but it must be because you have not defined $Colour_sf2 before use it in any function or condition.

"Cannot use a scalar value as an array" for undefined values

I have the following piece of code:
function Biz_GetAccountsPerMarket($site = "", $cache = true){
if($site == ""){
$site = $_SESSION["sitedirect_current_site"];
}
$aAccounts = Sys_OptionsGet("sys_site/".$site, "account", $cache);
$aAccountInfo = array();
$aVatAccount = Biz_GetVatAccounts($site, $cache);
$aSalesAccount = Biz_GetSalesAccounts($site, $cache);
foreach((array)$aAccounts as $code => $data){
foreach((array)$data["data"] as $market => $aItem){
$aAccountInfo[$market][$code] = $aItem;
$aAccountInfo[$market][$code]["vat"] = $aVatAccount[$aItem["vat_account_code"]]["value"];
$aAccountInfo[$market][$code]["vat_account"] = $aVatAccount[$aItem["vat_account_code"]]["account"];
$aAccountInfo[$market][$code]["sales_account"] = $aSalesAccount[$aItem["sales_account_code"]]["account"];
}
}
return $aAccountInfo;
}
The four innermost lines in the nested loop generates warnings: "Cannot use a scalar value as an array".
Adding lines that initialises $aAccountInfo[$market] and $aAccountInfo[$market][$code] to empty arrays first silences the errors, but this is far from the only place in our code where nested arrays are initialised in this way; and I can't figure out why it is a problem in the first place.
The following code should reproduce the problem; as far as I can tell; but doesn't:
<?php
ini_set('display_errors', '1');
error_reporting(E_ALL | E_STRICT);
$aTest = [];
$aTest['key']['key'] = 'sausage';
If $aItem was a string or false, or any scalar; I could understand what the problem is; but then the warning should only happen for the last three lines, not all four.
There are other weird things happening there, I hope they're all connected. This is the only one I've managed to isolate enough to ask a question about.
Is it possble to set the default value created by array access somehow?
edit:
I've noticed that many strings that are generates have an extraneous "0". This breaks things, like SQL. If empty array values somehow default to "0" or something, that would explain a lot. I have no idea how that could happen though. I'm currently grepping for "register_tick_function"...
You need to check if arrays have the expected keys. Something like this:
$aAccountInfo[$market][$code]["vat"] = isset($aItem["vat_account_code"]) ? (isset($aVatAccount[$aItem["vat_account_code"]]) ? $aVatAccount[$aItem["vat_account_code"]]["value"] : []) : [];
I am afraid your code is wrong
This line
$aAccountInfo[$market][$code] = $aItem;
creates the new occurance containing a SCALAR value and you then try and add a sub array onto that scalar value, hence the error
If you do this instead
$t = array();
$t['item'] = $aItem;
$t["vat"] = $aVatAccount[$aItem["vat_account_code"]]["value"];
$t["vat_account"] = $aVatAccount[$aItem["vat_account_code"]]["account"];
$t["sales_account"] = $aSalesAccount[$aItem["sales_account_code"]]["account"];
$aAccountInfo[$market][$code] = $t;
Then you will get a sub array created with all the values in it;

Undefined offset: 7 in /home/test/index.php

I am struggling with the undefined notice comes and sometimes not. I am not sure why I am having this error.
foreach($_POST['toplevel_menus'] as $toplevel_menu){
$toplevel_extracted = explode("|", $toplevel_menu);
$submenu_id = $toplevel_extracted[5];
if(isset($_POST[$submenu_id]) && !empty($_POST[$submenu_id])){
foreach($_POST[$submenu_id] as $submenu){
$extracted = explode("|" $submenu);
$submenu_name = (isset($_POST[$subname][$extracted[1]]))
? trim($_POST[$subname][$extracted[1]])
: "";
}
}
}
The line number 7 is
$submenu_name = (isset($_POST[$subname][$extracted[1]])) ? trim($_POST[$subname][$extracted[1]]) : "";
The best practice to always access arrays via index is to check them with isset first. This way you can make sure to avoid such errors.

Warning: implode(): Invalid arguments passed in functions.php on line 674

i tried to go online after finishing the website but a error occurs
Warning: implode(): Invalid arguments passed in functions.php on line 674
foreach ( $one_array_font as $font => $variants ) {
$font = str_replace(' ', '+', $font);
$variants = implode(',', array_values($variants['variant']) );
$all_final_fonts[] = $font.':'.$variants;
}
$gfont = implode('|', $all_final_fonts); /* <-- This line fails */
wp_enqueue_style( 'zn_all_g_fonts', '//fonts.googleapis.com/css?family='.$gfont.''.$subset);
if ( $data['zn_main_style'] == 'dark' ) {
wp_enqueue_style('zn-dark-style', get_template_directory_uri() . '/css/dark-theme.css',array() ,false,'all');
}
if ( !empty ( $data['g_fonts_subset'] ) ) {
$subset = '&subset='.str_replace( ' ' , '' , $data['g_fonts_subset']);
}
Not really enough info in the question, but this is what I think is happening:
Firstly, $one_array_font is empty.
This means that the foreach() loop is never run.
This means that the line $all_final_fonts[] = $font.':'.$variants; is never run.
I'm guessing that $all_final_fonts was not defined earlier. Therefore it is still undefined when the code gets to the implode.
The implode() fails because it requires the input field to be an array, but you've given it an undefined variable.
Solution
Ensure that $all_final_fonts is defined regardless, by adding the following line before the foreach() loop:
$all_final_fonts = array();
This will initialise the variable as an array, so that implode() won't complain about it if you don't have any data.
Hope that helps.
You are seeing that warning because $all_final_fonts is not an array.
See http://php.net/manual/en/function.implode.php
regards

Uninitialized string offset while building array

I am getting the following error from the method presented below:
Notice: Uninitialized string offset: 5 in /path/to/file.php on line 30 Fatal error: Cannot access empty property in path/to/file.php on line 30
private function parse($xml, $index = '') {
echo count($xml->children()); //outputs 6
$count = 0;
foreach ($xml->children() as $key => $value) {
$this->$key[$count] = array();
$count++;
}
}
Any ideas why if I build an multi-dimensional in this way it results in an error?
If I change the assignment to:
$this->$key = array($count = > array());
This simply re-assigns the property each loop.
Thanks
Rich
Imagine you've got a string:
$string = 'abc`;
Doing substring access (which looks like array) will return you the character:
echo $string[2]; # c
Or you get your error when you're out of the index:
echo $string[3]; # null + warning
So now accessing a member of your object $this dynamically:
$this->$string[2]; # access $this->c
However this one breaks hardly:
$this->$string[3]; # access $this->null (not possible)
This gives you your fatal error of an empty property, a property with no name.
This explain what happens in your code, you have not told what you're trying to do so I hope this information will help you to continue with writing your parse function.
You should try to create the array before filling it.
I.e. $this->key = array();
That is, before looping through the XML elements.

Categories