Reputation: 1385
I have just been shown the method to remove numbers with more than 2 decimal places from an array [here]. The thing is when i try to format the output using echo instead of var_dump as such:
$line = 1;
for($i = 1; $i < count($value1); $i++){
echo "$line | ".$value1[$i][0]." | ".$value1[$i][1]." | ".$value1[$i][2]." | ".$value1[$i][3]." | ".$value1[$i][4].'<br>';
$line = $line + 1;
}
I get many "Notice: Undefined offset: " all over the place. Is there a way to reset the rows in the array?
The reason i need to format it with "echo" is so that i can copy the output directly and paste it into a document without having to delete the unnecessary characters from "var_dump". Am i doing it wrong?
Thanx in advance...
Thanx in advance.
Upvotes: 0
Views: 109
Reputation: 96
You could use a few ways to either remove or ignore the array elements without PHP throwing notices:
$line = 1;
for($i = 1; $i < count($value1); $i++){
if( isset( $value[$i][0]) === TRUE && isset( $value[$i][1]) === TRUE && isset( $value[$i][2]) === TRUE && isset( $value[$i][3]) === TRUE && isset( $value[$i][4]) === TRUE )
{
echo "$line | ".$value1[$i][0]." | ".$value1[$i][1]." | ".$value1[$i][2]." | ".$value1[$i][3]." | ".$value1[$i][4].'<br>';
}
$line = $line + 1;
}
or you could use count($value[$i][0]) > 0 to ensure the array has a value contained.
Upvotes: 1
Reputation: 1385
Solved it. After the:
function decimalFilter($v) {
foreach ( $v as $x ) {
if (strlen(substr(strrchr($x, "."), 1)) > 2)
return false;
}
return true;
}
$value = array_filter($value, "decimalFilter");
Then i add:
sort($value);
followed by:
for($i = 1; $i < count($value); $i++){
echo $value[$i][0]." | ".$value[$i][1]." | ".$value[$i][2]." | ".$value[$i][3]." | ".$value[$i][4].'<br>';
}
The missing elements disappeared during output. Thing is i dunno if this is a practical approach as yet.
Upvotes: 1
Reputation: 1783
I don't know how the array looks like, but one error you are having in your code for sure is:
for($i = 1; $i < count($value1); $i++)
in PHP an array starts with the index 0
, you need to correct your code like this:
for($i = 0; $i < count($value1); $i++)
or use foreach which is a lot easier.
Upvotes: 1
Reputation: 5351
What about using implode instead of the unhandy concatenation?
<?php
foreach ($value1 as $counter => $line){
echo ($counter + 1) . " | ". implode(" | ", $line) . '<br>';
}
This way, it's ensured that only existing values are concatenated. If you still want to remove elements from an array, you might consider checking them for emptyness and using unset after that.
Upvotes: 2