.
🙂 Hey!
halojoy here
Just a little addition, as this is resolved.
To unset and delete one value from an indexed array.
And fix indexes so that they match set values
and be able to use for() loop listing and/or address any indexed values directly without looping.
Indexed array is a numbered array, like:
$my_arr[0], $my_arr[1], $my_arr[2], $my_arr[3], $my_arr[4]
Note: corrupted indexes, after unset, does not effect foreach() loops
as foreach() only includes index/element that isset.
I have run and tested this script.
It shows what can happen and howto fix it.
/yours halojoy
in late northern swedish summer
<?php
error_reporting( E_ALL &~ E_NOTICE );
// This is not a problem when using foreach() loop
// But with foreach you can not address 1 value
// without looping to find it ( takes time )
// Task: to delete "jack" and make an array with 5 elements
// Each value can be addressed with its index
// and for() loop can be used to list without problem
// indexes will finally be [0] [1] [2] [3] [4], as "0" is used for first index
// Create array with 5 elements + one disturbing "jack"
$my_arr = array( "zero","one","jack","two","three","four" );
$num = count($my_arr);
echo "Step1<br>
Count returns $num set values<br>
and same number of indexes exist<br>";
// display original values and find index of "jack"
for ($i=0;$i<$num;$i++) {
echo "$i $my_arr[$i] <br>";
if( $my_arr[$i] == "jack" ) $idx = $i;
}
// unset index with "jack"
unset( $my_arr[$id ] );
$num = count($my_arr);
echo "<hr>Step2<br>'jack' was unset ( index = $idx )<br>
Count returns $num set values<br>
but original number of indexes still exist<br>
<font color='red'>So last value is NOT within for() loop</font><br>";
for ($i=0;$i<$num;$i++) {
echo "$i $my_arr[$i] <br>";
}
// Make a new array, of indexed elements that have VALUE,
// that is, any element that isset ( not unset )
// function for this is: array_values( $arr_name )
// To fix index numbering after unset,
// instead of 2 lines like here, you can make it:
// $my_arr = array_values( $my_arr );
$new_arr = array_values( $my_arr );
$my_arr = $new_arr;
$num = count($my_arr);
echo "<hr>Step3<br>
function array_values() was run<br>
Count returns $num set values<br>
and number of indexes match again<br>
<font color='green'>All values are within for() loop</font><br>";
for ($i=0;$i<$num;$i++) {
echo "$i $my_arr[$i] <br>";
}
echo "<hr><b><i>THE END</i></b>";
exit;
?>