PHP explode only working when I suppress error - php

I am using the explode function in php to split a string like "60-5000"
into two elements that can be cast to integers.
$parts = explode('-', '60-5000',2);
$this->p1 = (integer)$parts[0];
$this->p2 = (integer)#$parts[1];
When this is ran in the constructor of my class I am getting this error:
Undefined offset: 1
When I suppress the error on the second element of the array I obtain the correct array
0 => "60"
1 => "5000"
Above is the debug statement with error suppressed on the second index.
I do not want to keep having to suppress this error to get the results from explode. Is there something wrong with my implementation?

Related

Undefined variable in create_function() parameter?

I'm trying to use create_function in order to find out how many times a certain value occurs in a particular array.
while (!empty($rollcounts)){
// Take the first element of $rollcounts
$freq = count(array_filter($rollcounts,create_function("$a","return $a == $rollcounts[0]")));// Count how many times the first element of $rollcounts occurs in the list.
$freqs[$rollcounts[0]] = $freq; // Add the count to the $frequencies list with associated number of rolls
for($i=0;$i<count($rollcounts);$i++){ // Remove all the instances of that element in $rollcounts
if(rollcounts[$i] == $rollcounts[0]){
unset($rollcounts[$i]);
}
}
} // redo until $rollcounts is empty
I get a "Notice" message complaining about the $a in create_function(). I'm surprised, because I thought $a was simply a parameter. Is create_function() not supported in my version of php? phpversion() returns 5.6.30 and I'm using XAMPP. The error message:
Notice: Undefined variable: a in /Applications/XAMPP/xamppfiles/htdocs/learningphp/myfirstfile.php on line 34
So, if I'm reading your question correctly, I think you want to count the occurrences of each element in the array? If so just use array_count_values e.g. [1, 1, 2, 2, 3] -> [1 => 2, 2 => 2, 3 => 1]
$freqs = array_count_values($rollcounts);
This way you can skip your while loop.
You should use something like ...
$freq = count(array_filter($rollcounts,function($a) {return $a == $rollcounts[0];}));
Have a read of http://php.net/manual/en/functions.anonymous.php which explains a bit more about them.

PHP notices - undefined [duplicate]

I am receiving the following error in PHP
Notice undefined offset 1: in C:\wamp\www\includes\imdbgrabber.php line 36
Here is the PHP code that causes it:
<?php
# ...
function get_match($regex, $content)
{
preg_match($regex,$content,$matches);
return $matches[1]; // ERROR HAPPENS HERE
}
What does the error mean?
If preg_match did not find a match, $matches is an empty array. So you should check if preg_match found an match before accessing $matches[0], for example:
function get_match($regex,$content)
{
if (preg_match($regex,$content,$matches)) {
return $matches[0];
} else {
return null;
}
}
How to reproduce this error in PHP:
Create an empty array and ask for the value given a key like this:
php> $foobar = array();
php> echo gettype($foobar);
array
php> echo $foobar[0];
PHP Notice: Undefined offset: 0 in
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) :
eval()'d code on line 1
What happened?
You asked an array to give you the value given a key that it does not contain. It will give you the value NULL then put the above error in the errorlog.
It looked for your key in the array, and found undefined.
How to make the error not happen?
Ask if the key exists first before you go asking for its value.
php> echo array_key_exists(0, $foobar) == false;
1
If the key exists, then get the value, if it doesn't exist, no need to query for its value.
Undefined offset error in PHP is Like 'ArrayIndexOutOfBoundException' in Java.
example:
<?php
$arr=array('Hello','world');//(0=>Hello,1=>world)
echo $arr[2];
?>
error: Undefined offset 2
It means you're referring to an array key that doesn't exist. "Offset"
refers to the integer key of a numeric array, and "index" refers to the
string key of an associative array.
Undefined offset means there's an empty array key for example:
$a = array('Felix','Jon','Java');
// This will result in an "Undefined offset" because the size of the array
// is three (3), thus, 0,1,2 without 3
echo $a[3];
You can solve the problem using a loop (while):
$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
// Increase count by 1, thus, $i=1
$i++;
$groupname[$i] = base64_decode(base64_decode($row['groupname']));
// Set the first position of the array to null or empty
$groupname[0] = "";
}

php difference between pack() and unpack()

in php 4.4.4 having:
$hbc=pack("LL",82603088,82602992);
list($v1,$v2)=unpack("L2",$hbc);
echo("v1=".$v1." v2=".$v2);
result is:
v1= v2=82603088
I already have some hours wrapping my head aroud this...
thanks
The error is not withing the pack or unpack, but inside the list().
Turn on notices! Your code will complain like this:
Notice: Undefined offset: 0 in ...
That should make you wonder. If you dump the array that is returned by unpack, it is correct:
array(2) {
[1] =>
int(82603088)
[2] =>
int(82602992)
}
And then there is this tiny little note on the docs page of list():
list() only works on numerical arrays and assumes the numerical indices start at 0.
Your array does not start at index 0, and the notice likes to tell you that.
The quick fix is:
list(,$v1,$v2)=unpack("L2",$hbc); // add a comma to skip index 0
A better approach might be to use unpack to create named array indices:
$unpacked = unpack("L2v/",$hbc);
Result:
array(2) {
'v1' =>
int(82603088)
'v2' =>
int(82602992)
}
From the php.net comments.
$int_list = array_merge(unpack("s*", $some_binary_data));
This will essentially reset your index keys starting at 0.

PHP Notice: Undefined offset: 1 with array when reading data

I am getting this PHP error:
PHP Notice: Undefined offset: 1
Here is the PHP code that throws it:
$file_handle = fopen($path."/Summary/data.txt","r"); //open text file
$data = array(); // create new array map
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle); // read in each line
$parts = array_map('trim', explode(':', $line_of_text, 2));
// separates line_of_text by ':' trim strings for extra space
$data[$parts[0]] = $parts[1];
// map the resulting parts into array
//$results('NAME_BEFORE_:') = VALUE_AFTER_:
}
What does this error mean? What causes this error?
Change
$data[$parts[0]] = $parts[1];
to
if ( ! isset($parts[1])) {
$parts[1] = null;
}
$data[$parts[0]] = $parts[1];
or simply:
$data[$parts[0]] = isset($parts[1]) ? $parts[1] : null;
Not every line of your file has a colon in it and therefore explode on it returns an array of size 1.
According to php.net possible return values from explode:
Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.
If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.
How to reproduce the above error in PHP:
php> $yarr = array(3 => 'c', 4 => 'd');
php> echo $yarr[4];
d
php> echo $yarr[1];
PHP Notice: Undefined offset: 1 in
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) :
eval()'d code on line 1
What does that error message mean?
It means the php compiler looked for the key 1 and ran the hash against it and didn't find any value associated with it then said Undefined offset: 1
How do I make that error go away?
Ask the array if the key exists before returning its value like this:
php> echo array_key_exists(1, $yarr);
php> echo array_key_exists(4, $yarr);
1
If the array does not contain your key, don't ask for its value. Although this solution makes double-work for your program to "check if it's there" and then "go get it".
Alternative solution that's faster:
If getting a missing key is an exceptional circumstance caused by an error, it's faster to just get the value (as in echo $yarr[1];), and catch that offset error and handle it like this: https://stackoverflow.com/a/5373824/445131
Update in 2020 in Php7:
there is a better way to do this using the Null coalescing operator by just doing the following:
$data[$parts[0]] = $parts[1] ?? null;
This is a "PHP Notice", so you could in theory ignore it. Change php.ini:
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
To
error_reporting = E_ALL & ~E_NOTICE
This show all errors, except for notices.
my quickest solution was to minus 1 to the length of the array as
$len = count($data);
for($i=1; $i<=$len-1;$i++){
echo $data[$i];
}
my offset was always the last value if the count was 140 then it will say offset 140 but after using the minus 1 everything was fine
The ideal solution would be as below. You won't miss the values from 0 to n.
$len=count($data);
for($i=0;$i<$len;$i++)
echo $data[$i]. "<br>";
In your code:
$parts = array_map('trim', explode(':', $line_of_text, 2));
You have ":" as separator. If you use another separator in file, then you will get an "Undefined offset: 1" but not "Undefined offset: 0" All information will be in $parts[0] but no information in $parts[1] or [2] etc. Try to echo $part[0]; echo $part[1]; you will see the information.
I just recently had this issue and I didn't even believe it was my mistype:
Array("Semester has been set as active!", true)
Array("Failed to set semester as active!". false)
And actually it was! I just accidentally typed "." rather than ","...
The output of the error, is because you call an index of the Array that does not exist, for example
$arr = Array(1,2,3);
echo $arr[3];
// Error PHP Notice: Undefined offset: 1 pointer 3 does not exist, the array only has 3 elements but starts at 0 to 2, not 3!

Undefined offset 1

I am facing a problem that undefined offset :1 in line 3. I can't understand that what type of error it is.
Can anyone tell me that why such error occurs in php
Undefined offset in line : 3
foreach ($lines as $line)
{
list($var,$value) = explode('=', $line); //line 3
$data[$var] = $value;
}
Your are getting PHP notice because you are trying to access an array index which is not set.
list($var,$value) = explode('=', $line);
The above line explodes the string $line with = and assign 0th value in $var and 1st value in $value. The issue arises when $line contains some string without =.
I know this an old question and the answer provided is sufficient.
Your are getting PHP notice because you are trying to access an array
index which is not set.
But I believe the best way to overcome the problem with undefined indexes when there are cases where you may have an empty array using the list()/explode() combo is to set default values using array_pad().
The reason being is when you use list() you know the number of variables you want from the array.
For example:
$delim = '=';
$aArray = array()
$intNumberOfListItems = 2;
list($value1, $value2) = array_pad(explode($delim, $aArray, $intNumberOfListItems ), $intNumberOfListItems , null);
Essentially you pass a third parameter to explode stating how many values you need for your list() variables (in the above example two). Then you use array_pad() to give a default value (in the above example null) when the array does not contain a value for the list variable.
This is caused because your $line doesn't contain "=" anywhere in the string so it contains only one element in array.list() is used to assign a list of variables in one operation. Your list contains 2 elements but as from data returned by implode, there is only one data. So it throws a notice.
A way to overcome that is to use array_pad() method.
list($var,$value) = array_pad(explode('=', $line),2,null);
by doing list($var, $value) php will expect an array of 2 elements, if the explode function doesn't find an equal symbol it will only return an array with 1 element causing the undefined offset error, offset 1 is the second element of an array so most likely one of your $line variables doesn't have an equal sign
This is due to the array. The array index is not showing due to this undefine offset error will come...
So please check the array with print_r function.
The list language construct is used to create individual variables from an array. If your array doesn't have enough elements for the number of variables you are expecting in the list call, you will get an error. In your case you have 2 variables so you need an array with 2 items - indexes 0 and 1.
http://php.net/manual/en/function.list.php
Solution:
$lines = array('one' => 'fruit=apple', 'two' => 'color=red', 'three' => 'language');
foreach ($lines as $line)
{
list($var,$value) = (strstr($line, '=') ? explode('=', $line) : array($line, ''));
$data[$var] = $value;
}
print_r($data);
Try this one..
For reference
http://in1.php.net/manual/en/function.list.php
http://in1.php.net/manual/en/function.explode.php

Categories