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
Related
Example:
$array = ['name', 'address'];
It contains $array[0] and $array[1] only.
If i try $array[2] i should receive an error.
So, i want to avoid these errors by checking it in a if statement. How can i check if an array contains a value in certain index?
You can use the isset function:
if(isset($array[2])) {
The second way to make it work is check how big is an array:
if(count($array) >= 3) { ... } // three or more elements: 0, 1, 2...
I'm looking for a simple function which will remove blank or duplicate variables from a query string in PHP. Take this query string for example:
?input=timeline&list=&search=&type=&count=10&keyword=hello&from=&language=en&keyword=&language=en&input=timeline
As you can see there are two input=timeline and the language and keyword variables appear twice- once set and once not. Also there are lots of variables that are blank- list, search and type.
What function would clean the URL up to make:
?input=timeline&count=10&keyword=hello&from=&language=en
?
I've found functions that remove queries, or certain variables, but nothing that comes close to the above- I can't get my head round this. Thanks!
I'd suggest simply taking advantage of PHP's parse_str, but as you mentioned, you've got multiple keys that are the same and parse_str will overwrite them simply by the order they're given.
This approach would work to favor values that are not empty over values that are, and would eliminate keys with empty values:
$vars = explode('&', $_SERVER['QUERY_STRING']);
$final = array();
if(!empty($vars)) {
foreach($vars as $var) {
$parts = explode('=', $var);
$key = $parts[0];
$val = $parts[1];
if(!array_key_exists($key, $final) && !empty($val))
$final[$key] = $val;
}
}
If your query were input=value&input=&another=&another=value&final=, it would yield this array:
[input] => value
[another] => value
...which you could then form into a valid GET string with http_build_query($final).
"?" . http_build_query($_GET) should give you what you want. Since $_GET is an associative array any duplicate keys would already be overwritten with the last value supplied in the query string.
I have an array that has 120~ or so offsets and I was wondering how you would delete all the values of said array after a certain offset containing a specified string. For example: Offset [68] has the string 'Overflow'. I want to remove everything including 68 and beyond and rebuild the array (with its current sorting in tact).
I tried messing around with slice and splice but I can't seem to get it to return the right values. I was also thinking of just grabbing the offset number that contains 'Overflow' and then looping it through a for statement until $i = count($array); but that seems a little more intensive than it should be.
Would this be the best way? Or is there some function to do this that I'm just using wrong?
Use array_slice().
$desired = array_slice($input, 0, $upTo);
First you need to find the string occurrence in the array, and, if the value was found, trim the array from that point;
function removeString($string, $array)
{
# search for '$string' in the array
$found = array_search($string, $array);
if ($found === false) return $array; # found nothing
# return sliced array
return array_slice($array, $found);
}
And if you need to make the array sequential (to avoid surprises due to missing offsets), you can always add in the first line $array = array_values($array). This will reorganize the array values in a new array with ordered offsets: 0, 1, 2, 3, 4...
I don't understand the each() and the list() function that well. Can anyone please give me a little more detail and explain to me how can it be useful?
Edit:
<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?>
Array
(
[1] => bob
[value] => bob
[0] => 0
[key] => 0
)
So does this mean in array[1] there's the value bob, but it's clearly in array[0]?
list is not a function per se, as it is used quite differently.
Say you have an array
$arr = array('Hello', 'World');
With list, you can quickly assign those different array members to variables
list($item1, $item2) = $arr; //$item1 equals 'Hello' and $item2 equals 'World'
The each() function returns the current element key and value, and moves the internal pointer forward.
each()
The list function — Assigns variables as if they were an array
list()
Example usage is for iteration through arrays
while(list($key,$val) = each($array))
{
echo "The Key is:$key \n";
echo "The Value is:$val \n";
}
A very common example for list is when thinking about CSV files. Imagine you have a simple database stored as CSV with the columns id, title and text, such a file could look like this:
1|Foo|Lorem ipsum dolor|
2|Bar|sit amet|
...
Now when you parse this file you could do it like this, using the list function:
$lines = file( 'myFile.csv' );
for ( $i = 0; $i < count( $lines ); $i++ )
{
list( $id, $title, $text, $null ) = explode( '|', $lines[$i], 4 );
echo "Id: $id, Title: $title\n$text\n\n";
}
The other function, each, is basically just an old way to walk through arrays, using internal pointers. A more common way to do that is by using foreach now.
Edit: its probably worth noting that each has been deprecated
Warning: This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged
lets look first at each() : it returns the current value (at first that's $array[0 | "first value in association array ] . so
$prices = ('x'=>100 , 'y'=>200 , 'z'= 300 );
say I wanna loop over these array without using a foreach loop .
while( $e = each($prices) ){
echo $e[key] . " " . $e[value] . "<br/>" ;
}
when each reaches point at a non existing element that would cause
the while loop to terminate .
When you call each(), it gives you an array with four values and the four indices to the array locations.The locations 'key' and 0 contain the key of the current element, and the locations 'value' and 1 contain the
value of the current element.
so this loop would list each key of the array a space and the value then
secondly lets look at list() .
it basically will do the same thing with renaming of 'value' and 'key' although it has to be use in conjunction with each()
while( list($k , $v ) = each($prices) ){
echo $k /*$e[key]*/ . " " . $v /*$e[value]*/ . "<br/>" ;
}
So in a nutshell each() iterates over the array each time returning an array . list() rename the value , key pairs of the array to be used inside the loop .
NOTICE : reset($prices) :
resets each() pointer for that array to be the first element .
http://www.php.net/list
list isn't a function, it is a language construct. It is used to assign multiple values to different variables.
list($a, $b, $c) = array(1, 2, 3);
Now $a is equal to 1, and so on.
http://www.php.net/each
Every array has an internal pointer that points to an element in its array. By default, it points to the beginning.
each returns the current key and value from the specified array, and then advances the pointer to the next value. So, put them together:
list($key, $val) = each($array);
The RHS is returning an array, which is assigned to $key and $val. The internal pointer in `$array' is moved to the next element.
Often you'll see that in a loop:
while(list($key, $val) = each($array)):
It's basically the same thing as:
foreach($array as $key => $val):
To answer the question in your first edit:
Basically, PHP is creating a hybrid array with the key/value pair from the current element in the source array.
So, you can get the key by using $bar[0] and the value by using $bar[1]. OR, you can get the key by using $bar['key'] and the value using $bar['value']. It's always a single key/value pair from the source array, it's just giving you two different avenues of accessing the actual key and actual value.
Say you have a multi-dimensional array:
+---+------+-------+
|ID | Name | Job |
| 1 | Al | Cop |
| 2 | Bob | Cook |
+---+------+-------+
You might do something like:
<?php
while(list($id,$name,$job) = each($array)) {
echo "".$name." is a ".$job;
}
?>
Using them together is, basically, an early way to iterate over associative arrays, especially if you didn't know the names of the array's keys.
Nowadays there's really no reason I know of not to just use foreach instead.
list() can be used separately from each() in order to assign an array's elements to more easily-readable variables.
If I had an array like:
$array['foo'] = 400;
$array['bar'] = 'xyz';
And I wanted to get the first item out of that array without knowing the key for it, how would I do that? Is there a function for this?
reset() gives you the first value of the array if you have an element inside the array:
$value = reset($array);
It also gives you FALSE in case the array is empty.
PHP < 7.3
If you don't know enough about the array (you're not sure whether the first key is foo or bar) then the array might well also be, maybe, empty.
So it would be best to check, especially if there is the chance that the returned value might be the boolean FALSE:
$value = empty($arr) ? $default : reset($arr);
The above code uses reset and so has side effects (it resets the internal pointer of the array), so you might prefer using array_slice to quickly access a copy of the first element of the array:
$value = $default;
foreach(array_slice($arr, 0, 1) as $value);
Assuming you want to get both the key and the value separately, you need to add the fourth parameter to array_slice:
foreach(array_slice($arr, 0, 1, true) as $key => $value);
To get the first item as a pair (key => value):
$item = array_slice($arr, 0, 1, true);
Simple modification to get the last item, key and value separately:
foreach(array_slice($arr, -1, 1, true) as $key => $value);
performance
If the array is not really big, you don't actually need array_slice and can rather get a copy of the whole keys array, then get the first item:
$key = count($arr) ? array_keys($arr)[0] : null;
If you have a very big array, though, the call to array_keys will require significant time and memory more than array_slice (both functions walk the array, but the latter terminates as soon as it has gathered the required number of items - which is one).
A notable exception is when you have the first key which points to a very large and convoluted object. In that case array_slice will duplicate that first large object, while array_keys will only grab the keys.
PHP 7.3+
PHP 7.3 onwards implements array_key_first() as well as array_key_last(). These are explicitly provided to access first and last keys efficiently without resetting the array's internal state as a side effect.
So since PHP 7.3 the first value of $array may be accessed with
$array[array_key_first($array)];
You still had better check that the array is not empty though, or you will get an error:
$firstKey = array_key_first($array);
if (null === $firstKey) {
$value = "Array is empty"; // An error should be handled here
} else {
$value = $array[$firstKey];
}
Fake loop that breaks on the first iteration:
$key = $value = NULL;
foreach ($array as $key => $value) {
break;
}
echo "$key = $value\n";
Or use each() (warning: deprecated as of PHP 7.2.0):
reset($array);
list($key, $value) = each($array);
echo "$key = $value\n";
There's a few options. array_shift() will return the first element, but it will also remove the first element from the array.
$first = array_shift($array);
current() will return the value of the array that its internal memory pointer is pointing to, which is the first element by default.
$first = current($array);
If you want to make sure that it is pointing to the first element, you can always use reset().
reset($array);
$first = current($array);
another easy and simple way to do it use array_values
array_values($array)[0]
Just so that we have some other options: reset($arr); good enough if you're not trying to keep the array pointer in place, and with very large arrays it incurs an minimal amount of overhead. That said, there are some problems with it:
$arr = array(1,2);
current($arr); // 1
next($arr); // 2
current($arr); // 2
reset($arr); // 1
current($arr); // 1 !This was 2 before! We've changed the array's pointer.
The way to do this without changing the pointer:
$arr[reset(array_keys($arr))]; // OR
reset(array_values($arr));
The benefit of $arr[reset(array_keys($arr))]; is that it raises an warning if the array is actually empty.
Test if the a variable is an array before getting the first element. When dynamically creating the array if it is set to null you get an error.
For Example:
if(is_array($array))
{
reset($array);
$first = key($array);
}
We can do
$first = reset($array);
Instead of
reset($array);
$first = current($array);
As reset()
returns the first element of the array after reset;
You can make:
$values = array_values($array);
echo $values[0];
Use reset() function to get the first item out of that array without knowing the key for it like this.
$value = array('foo' => 400, 'bar' => 'xyz');
echo reset($value);
output //
400
Starting with PHP 7.3.0 it's possible to do without resetting the internal pointer. You would use array_key_first. If you're sure that your array has values it in then you can just do:
$first = $array[array_key_first($array)];
More likely, you'll want to handle the case where the array is empty:
$first = (empty($array)) ? $default : $array[array_key_first($array)];
You can try this.
To get first value of the array :-
<?php
$large_array = array('foo' => 'bar', 'hello' => 'world');
var_dump(current($large_array));
?>
To get the first key of the array
<?php
$large_array = array('foo' => 'bar', 'hello' => 'world');
$large_array_keys = array_keys($large_array);
var_dump(array_shift($large_array_keys));
?>
In one line:
$array['foo'] = 400;
$array['bar'] = 'xyz';
echo 'First value= ' . $array[array_keys($array)[0]];
Expanded:
$keys = array_keys($array);
$key = $keys[0];
$value = $array[$key];
echo 'First value = ' . $value;
You could use array_values
$firstValue = array_values($array)[0];
You could use array_shift
I do this to get the first and last value. This works with more values too.
$a = array(
'foo' => 400,
'bar' => 'xyz',
);
$first = current($a); //400
$last = end($a); //xyz