Undefined offset in 1 Error - php

i'm trying to exctract array with this code, but it gives that error. But if i remove while block from code and only give indice it works. Here is the code.
//This function gives error: Notice: Undefined offset: 1 in .......
//but if i delete while block and only write print $type[$i]; it works.
public function checkMimeType(){
echo '<pre>';
$i = 0;
$type = array();
foreach($this->_sourceFile as $key){
$type= $key['type'];
}
while($i <= count($type))
{
print $type[$i].'<br>';
$i++;
}
}

YOu're looping one time to often ;)
Index numbers start at zero. If there's one element in your array, the only index that is defined is therefore 0. count() will return 1.
If you loop 'till $i<= 1, it will stop at $i = 1. There is no element with the ID of 1.
So, instead, use while($i < count($type))

The count is not equal to the last index.
An array [x, y, z] has a count of 3, but the last index is 2.
So, in your while loop, you are not allowed to run until <= count, but only < count. When $ibecomes count the index is out of bounds already.

In your first loop you are not adding values to an array, you are overwriting the $type variable each time. Try this:
$type[] = $key['type'];
Edit: And also what #thst said

Related

PHP htag from h6 to h1 and getting array from zero and up in one loop

I got this code here:
$aNames = array("Band1","Band2","Band3","Band4","Band5","Band6");
sort($aNames);
for($i = count($aNames); $i > 0; $i-- ) {
echo "<h" .$i." align='center'>" . $aNames[$i-1] ." Is insane</h".$i.">";
}
it works. this code shows all the bands from h6 to h1 (from small to big)
and for getting the names out of the array from 0 to 5 it uses the same variable but then puts -1 after it. Is there anyone that can tell me why i had to do $i-1 so it would go "reversed" from 0 to 5? Because i dont really get it how that works.
We know that arrays are zero-indexed, So when you use count($aName) it returns 6 but on your existing array there is nothing like $aName[6], So to access the values of your $aName from then last to first you've to use $i-1. Hope this helps to understand it now.
But with your existing code- first of all where you used for() loop, you've do some refactoring like count($aName) the array length only once not in for() loop e.g
$aNames = array("Band1","Band2","Band3","Band4","Band5","Band6");
sort($aNames);
$count = count($aNames); // see the change here
for($i = $count; $i > 0; $i-- ) {
echo "<h" .$i." align='center'>" . $aNames[$i-1] ." Is insane</h".$i.">";
}
and You can also use index based array to avoid $i-1 way. Just use array like this format to keep track. Like as
$aNames = array(1=>"Band1",2=>"Band2",3=>"Band3",4=>"Band4",5=>"Band5",6=>"Band6");
Apart From your existing solution.You can easily do that using a foreach() without using any kind of $i-1. Just need to krsort() and foreach()
<?php
$aNames = array(1=>"Band1",2=>"Band2",3=>"Band3",4=>"Band4",5=>"Band5",6=>"Band6");
krsort($aNames);
foreach($aNames as $i=>$v){
echo "<h" .$i." align='center'>" . $aNames[$i] ." Is insane</h".$i.">";
}
Doing $i-1 does not reverse the array. Arrays are zero indexed so 0 is the first item. $aNames has 6 items, that means you could get the values using $aNames[0]...$aNames[5]
If you would write $aNames[$i] instead, your code would try to access $aNames[6] on the first iteration which will give an Undefined offset: 6
In this case you want the value of $i for <h1>...<h6> etc and the $i-1 to get the right index for $aNames[0]...$aNames[5].
Note that using sort in sort($aNames); does not change anything for the current data because it is already sorted.

PHP Array_intersect enters undefined offset

I got an array working like this:
$listaMaterias[x]['id_materia'] = (value with number and letters random)
$listaMaterias[x]['name_materia'] = (string)
$listaEditoriales[x]['id_editorial'] = (value with n. and l. random)
$listaEditoriales[x]['name_editorial'] = (string)
A 'materia' is a book's category. I made a foreach where I get all values from an xml right. Many editorials and materias, where some of them comes repeated.
And then, I make a method with an array_intersect to make remove repeated values, but I get an error :
$listaEdits_result = array(); // final results
$listaMats_result = array();
$listaEds_first_res = $listaEditoriales[0];
for ($j = 1 ; $j < count($listaEditoriales) ; $j++ ){
$listaEdits_result = array_intersect($listaEds_first_res, $listaEditoriales[$j]);
$listaEds_first_res = $listaEdits_result;
}
$listaMts_first_res = $listaMaterias[0];
for ($k = 1 ; $k < count($listaMaterias) ; $k++ ){
// Line 285, is this one above
$listaMats_result = array_intersect($listaMts_first_res, $listaMaterias[$j]);
$listaMts_first_res = $listaMats_result;
}
And finally, I get this error :
Notice: Undefined offset: 20 in [URL]/menu-librosnormales.php on line 285
Warning: array_intersect(): Argument #2 is not an array in [URL]/menu-librosnormales.php on line 285
Why access offset 20 if before I count this quantity in every array :
count($listaEditoriales) : 20
count($listaMaterias) : 14
Instead of $listaMaterias[$j] do $listaMaterias[$k] in second loop below line:-
$listaMats_result = array_intersect($listaMts_first_res, $listaMaterias[$j]);
Note:- If your aim is to remove duplicates from an array then you can use array_unique() easily.
In the second loop you use $listaMaterias[$j] but the loop is indexed by $k, not by $j.
The value of $j is count($listaEditoriales) because this was the last value of $j when the first loop ended. Since $listMaterias contains only 14 items, trying to access its 21st item triggers the notice you described.
If the purpose of each loop is to compute the intersection of the arrays stored in $listaEditoriales (and $listaMaterias) then you can do with a single call to array_intersect() using arguments unpacking (the so-called "splat operator"):
$listaEds_first_res = array_intersect(...$listaEditoriales);
$listaMts_first_res = array_intersect(...$listaMaterias);
The arguments unpacking operator is available since PHP 5.6. If you need to run the code on older PHP versions then you can use call_user_func_array() instead:
$listaEds_first_res = call_user_func_array('array_intersect', $listaEditoriales);
$listaMts_first_res = call_user_func_array('array_intersect', $listaMaterias);
The two lines of code above do the same thing as the entire block of code you posted in the question (faster and without errors).

reversing a for loop in php

I am very new to PHP. I have this code which outputs an array in reverse order. Although it works Im not sure why especially the $i = $num_items - 1 part of it. Any help would be greatly appreciated.
<?php
$characters = ['Arthur Dent', 'Ford Prefect', 'Zaphod Beeblebrox', 'Marvin', 'Slartibartfast'];
?>
<ul>
<?php
$num_items = count($characters);
for ($i = $num_items - 1; $i >= 0; $i--) {
echo "<li>$characters[$i]</li>";
}
?>
</ul>
Use array_reverse() function instead of a for loop ;)
http://php.net/manual/fr/function.array-reverse.php
In PHP, arrays index starts from 0, I'll explain:
Assume that you have 10 items in your array, they are stocked from index 0 to index 9. If you want to iterate through it, you have to start at 9 not 10. which is the number of items -1.
The array in php start from 0 and not 1, if you have array of n items then you can loop through it from 0 to n-1.
Since $i represents the index of the array, $num_items - 1 is because you start at index 0.
You can use the array_reverse() function and then use a foreach to iterate through the reversed array. You can also check the function asort() in case you would like to arrange the array in alphabetical order.
Hope that helps!!

Undefined offset: 1 For Loop PHP

The array it is fetching has size 2 , so if we comment out $size it returns 2 , but the for loop prints only the value present at 0th position of table column and not the next at 2th giving the error:
Undefined offset: 1
Code:
$allunstitched="Select p_id from unstitchedproduct";
$resultAllUnstitched= mysqli_query($connection,$allunstitched);
$AllUnstitchedResult= mysqli_fetch_array($resultAllUnstitched);
//$size=count($AllUnstitchedResult);
for ($i=0, $count = count($AllUnstitchedResult); $i < $count; ++$i) {
print $AllUnstitchedResult[$i];
}
You're using mysqli_fetch_array. This function returns the result twice by default: indexed both by number and by column name. Here the result set has only one column, so you get its value twice in the array: first with index 0 and then with a string index. There is no index 1.
To get the results with numerical indexes only, pass MYSQLI_NUM as a second argument to mysqli_fetch_array:
mysqli_fetch_array($resultAllUnstitched, MYSQLI_NUM);
Um, i dont think you have a problem in your for-loop; since your query reads ONE field/column it should have 1 iteration (=0 index), so the =1 undefined is correct (in my opinion).
What you should do is a loop that calls repeatedly mysqli_fetch_array to get all rows, like this:
while($AllUnstitchedResult = mysqli_fetch_array($resultAllUnstitched,MYSQLI_NUM)) {
foreach ($AllUnstitchedResult as $field) {
print $field;
}
}
If you start at 0, if count = 5 you'll have 6 elements (0,1,2,3,4,5), beware of that. You need to loop (count-1) times:
$count = count($AllUnstitchedResult);
for ($i=0, $i < $count-1; $i++) {
print $AllUnstitchedResult[$i];
}

PHP Undefined offset error repeated

I'm trying to run a PHP script that finds all the numbers divisible by 3 or 5, dumps them into an array, and adds all the values together. However, When I try to run it, I get a number output (I don't know if it's correct or not) and several hundred errors. They start out with:
Notice: Undefined offset: 1 in G:\Computer Stuff\WampServer\wamp\www\findthreesandfives.php on line 18
Then the offset number increases by increments of 1-3 (randomly, I haven't seen a pattern yet). I can't figure out what's wrong. Here's my code:
<?php
function loop($x)
{
$a = array(); //array of values divisible by 3 or 5
$l = 0; //length of the array
$e = 0; //sum of all the values in the array
for ($i=0; $i<=$x; $i++){ //this for loop creates the array
$n3=$i%3;
$n5=$i%5;
if($n3 === 0 || $n5 === 0){
$a[$i]=$i;
$l++;
}
}
for ($v=0; $v<=$l; $v++){ //this loop adds each value of the array to the total value
$e=$e + $a[$v];
}
return $e;
}
echo loop(1000);
?>
Someone please help...
The problem in your code is the following line:
$a[$i]=$i;
Should be:
$a[count($a)] = $i;
This is because the value of $i is always increasing, so using $i as your pointer will create gaps in the array's indices. count($a) returns the total number of items in the given array, which also happens to be the next index.
EDIT: #pebbl suggested using $a[] = $i; as a simpler alternative providing the same functionality.
EDIT 2: Solving the subsequent problem the OP described in the comments:
The problem seems to be that $l is greater than the number of items in $a. Thus, using count($a) in the for loop should fix your subsequent error.
Try replacing:
for ($v=0; $v<=$l; $v++){
With:
for ($v=0; $v<=count($a); $v++){
I found the same problem as #zsnow said. There are gaps within $a. The if condition allowed the gaps making the assignment skip some indexes. You can also use this
foreach ($a as $v){ //this loop adds each value of the array to the total value
$e=$e + $a[$v];
}
should actually be
foreach ($a as $v){ //this loop adds each value of the array to the total value
$e=$e + $v;
}

Categories