Browsing an array without knowing if content exists - php

So, what à do is trying to display the 3 first element of an array. Always 3. But, there is not always at least 3 elements.
So, what I've done is using an if :
<?php for ($i = 0; $i <= 2; $i++) { ?>
<?php if($post["Project"]["Post"][$i]){ ?>
...
<?php } ?>
<?php } ?>
But, I keep having "undefined offset" error when there is not 3 entries at least. Anyone with a solution ?

foreach (array_slice($array, 0, 3) as $item) {
echo $item;
...
}
or:
$i = 1;
foreach ($array as $item) {
...
if ($i++ >= 3) {
break;
}
}
foreach is always preferable to iterate arrays, precisely because you cannot access anything that doesn't exist.

Try the following:
<?php for ($i = 0; $i <= 2; $i++) {
if(isset($post["Project"]["Post"][$i])){ ?>
...
<?php }} ?>

Use isset() to check whether the key exists.
<?php if(isset($post["Project"]["Post"][$i])){ ?>
Or you could use:
$posts = $post["Project"]["Post"];
foreach ($posts as $i => $post) {
//...
if ($i === 2) break;
}

change it to if (isset($post ...
Alternatively:
foreach (array_slice($post["Project"]["Post"], 0, 3)) { ...

<?php for ($i = 0; $i <= 2; $i++) {
if( isset($post["Project"]["Post"][$i] )){
...
}
} ?>
you do not need <?php...?> tags for every line.

try ifset.
<?php for ($i = 0; $i <= 2; $i++) { ?>
<?php if(isset($post["Project"]["Post"][$i])){ ?>
...
<?php } ?>
<?php } ?>
Or, do a count first could be a way too.

Calculate before, which condition is met first (the actual size of the array or the max number - in your case 3) and then just traverse those elements:
$min = min( 3, count( $post["Project"]["Post"] ) );
for ($i = 0; $i < $min; $i++) {
if($post["Project"]["Post"][$i]){
...
}
}

Related

loop error in php code

Here is my code, and it is not removing $arr[5] element so that I am trying to remove strings starting with # from my array
this is code
<?php
$arr = [
'#EXTM3U',
'#EXTINF:177,Paul Dateh & Oren Yoel - Be More',
'Be More.mp3',
'#EXTINF:291,Christopher Toy - Just Because',
'Just Because.mp3',
'#EXTINF:238,Magnetic North - Drift Away',
'Drift Away.mp3'
];
for ($i = 0; $i <= count($arr); $i++) {
if ($arr[$i]{0} == '#') {
echo $arr[$i] . "\n";
unset($arr[$i]);
}
}
print_r($arr);
?>
Reason:- You are counting array length inside the loop and every time when any value got unset() from the array, length of array decreased and value of count($array) changed (simply decreased)
So logically your 5th and 6th element never goes through if condition (they never get traversed by loop because of decreasing length of the array )
Solution 1:- Put count outside and it will work properly:-
$count = count($arr);
//loop start from 0 so use < only otherwise, sometime you will get an undefined index error
for ($i = 0; $i < $count; $i++) {
if ($arr[$i]{0} == '#') {
//echo $arr[$i] . "\n";
unset($arr[$i]);
}
}
print_r($arr);
Output:-https://eval.in/996494
Solution 2:- That's why i prefer foreach() over for() loop
foreach($arr as $key=> $ar){
if ($ar[0] == '#') {
unset($arr[$key]);
}
}
print_r($arr);
Output:-https://eval.in/996502
more spacific :
for ($i = 0; $i < count($arr); $i++) {
if (strpos($arr[$i], '#') !== false) {
echo "<br/>";
} else {
echo $arr[$i]."<br/>";
}
}
Try to use additional array to push right values. You calc count($arr); each iteration and when you do count($arr); your array gets smaller and count($arr); returns smaller values, so last elements won't be comparing, try to use variable to calc count before loop make changes:
<?php
//...
$start_count = count($arr);
for ($i = 0; $i <= $start_count; $i++) {
if ($arr[$i]{0} == '#') {
echo $arr[$i] . "\n";
unset($arr[$i]);
}
}
Or remove bad element with a help of additional array, put good elements in new array and don't delete them from input array:
<?php
$arr = [
'#EXTM3U',
'#EXTINF:177,Paul Dateh & Oren Yoel - Be More',
'Be More.mp3',
'#EXTINF:291,Christopher Toy - Just Because',
'Just Because.mp3',
'#EXTINF:238,Magnetic North - Drift Away',
'Drift Away.mp3'
];
$cleared_from_mess_array = array();
for ($i = 0; $i <= count($arr); $i++) {
if ($arr[$i]{0} != '#')
{
array_push($cleared_from_mess_array,$arr[$i]);
}
}
print_r($cleared_from_mess_array);
exit;

Change foreach loop to a for loop

I'm quite new to PHP. How can I change this foreach loop to only loop twice?
<?php
foreach($results as $row):
?>
Try this code, you just need a counter variable, initialize your counter variable from zero and increment it after each iteration.
<?php
$counter = 0;
foreach($results as $row) {
//your code
if($counter == 1)
{
break;
}
$counter++;
}
?>
You could iterate up to the size of the array or 2 - the smaller of the two.
<?php
$maxInd = min(2, count($results);
for ($i = 0; $i < $maxInd; ++$i) {
$row = $results[$i];
// Do something interesting with $row
}
?>
<?php
for ($i = 0, $count = count($results); $i < $count; ++$i) {
var_dump($results[$i]);
// or assign it to $result variable
$result = $results[$i];
}
?>
But this will work only for collection there are some examples for example generators where you must use foreach.

for loop repeating in for each loop

I am having for loop in foreach loop
static $count=0;
for($i=$count;$i<$semesters_count;$i++)
{
echo $array_wam[$i];
$count++;
}
here $array_wam is array of some marks. I am printing multiple student marks
I getting first student marks
first student
50.6
second student
50.6 60.9
I want to show output like
first student
50.6
second student
60.9
Here loop again starts with 0 but I want loop starts with where it ends.
I dont know if i am understanding right what you are asking for but have you tried like this?
for($i=0;$i<$semesters_count;$i++){
echo $array_wam[$i];
}
For that you have to put static $count=0; before the foreach starts.
See an example below:
static $count=0;
foreach ($item)
{
for($i=$count;$i<$semesters_count;$i++)
{
echo $array_wam[$i];
$count++;
}
}
The problem is that you're not incrementing $count when you reach the end of the for loop.
Instead of incrementing $count inside the loop, set it to $i at the end of the loop:
static $count = 0;
for ($i = $count; $i < $semesters_count; $i++) {
echo $array_wam[$i];
}
$count = $i;
Try this :-
static $count = 0;
foreach ($item)
{
$semester_count_total = $semesters_count + $count;
for ($i = $count; $i < $semester_count_total; $i++) {
echo $array_wam[$i];
}
$count = $semester_count_total;
}
Try this:
for($i = 0; $i < $count_semester; $i++){
echo $array_wam[$i];
}
Why do you want static $count if it can loop trough for loop? And it still counters your $i variable is equal to the length of your $count_semester.

PHP Array, Get every 4 results and output in a loop

I'm trying to output my array results in groups of 4.
<?php for ($i = 0; $i < 4; ++$i) { ?>
<div>
// code
</div>
<?php } ?>
The above does 4, but obviously doesn't re-loop.
You can loop whole array and group you output with help of "%" operator.
<div>
<?php for ($i = 0; $i < count($array); $i++) {
if (($i % 4) == 0) {
echo "</div><div>";
}
echo "Element " . $array[$i]; // CODE
}
</div>
Other than using Mod as the other answers show, you could use array_chunk() to create the groups:
$groups = array_chunk($original_array, 4);
foreach($groups as $group){
echo '<div>';
foreach($group as $item){
echo $item;
}
echo '</div>';
}
You can use a while loop to reloop for the whole results to be printed
<?php while(conditions) {
for ($i = 0; $i < 4; ++$i) { ?>
<div>
// code
</div>
<?php } } ?>
Try this that way you can jump by 4
for ($i = 0; $i < 20; $i = $i+4) {
echo $i.'<br/>';
}
I would use a foreach and then just throw in an extra check to output the divs.
$i=0;
foreach ($array as $key->$val)
{
if($i%3==0)
{
echo "<div>";
}
// your stuff
if($i%3==0)
{
echo "</div>";
}
$i++;
}
array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.
you can check out from here http://php.net/manual/en/function.array-slice.php
try this, use nested for loop, this will loop 4 times. You can try to integrate with your code. If
for ($i = 0; $i < 4; $i++){
for($j = 0; $j < 4; $j++){
echo $a[$j++];
}
echo "<br/>";
}
I hope it can help you.
you can try $i++, because you use ++$i in this way "for" works 3 times!
for ($i = 0; $i < 4; $i++)

PHP - display 'X' items from foreach loop with link to display next 'X' items

I have a foreach loop which loops through an array (simpleXML nodes). This array can have between 0 and several hundred items in it. I'd like to find a way to display the first 10 results and then have a link to display the next 10 and so on.
for instance, I currently have:
$i=0;
$limit=10;
foreach ($nodes as $node){
echo "here is the output: ".$node."<br>\n";
if (++$i >=$limit) break;
}
obviously, no matter how many items are in the $nodes array, it only displays the first 10. But I think I read that foreach loops reset the counter every time they run - so if I wanted to have a link that said: next 10 itmes - I'm not sure how I would tell the the loop to start on index=10.
Am I even barking up the right tree here?
This is called pagination. You could extract the segment of the array that you need with array_slice: http://php.net/array_slice
<?php
$page = isset($_GET['page']) ? intval($_GET['page']) : 0;
$elementsPerPage = 10;
$elements = array_slice($nodes, $page * $elementsPerPage, $elementsPerPage);
foreach($elements as $node)
{
echo "Here is the output: ".$node."<br>\n";
}
Then you only need a link that points to the same page with the argument ?page=$page+1
Well, you could use a LimitIterator...
$offset = (int) (isset($_GET['offset']) ? $_GET['offset'] : 0);
$limit = 10;
$arrayIterator = new ArrayIterator($nodes);
$limitIterator = new LimitIterator($arrayIterator, $offset, $limit);
$n = 0;
foreach ($limitIterator as $node) {
$n++;
//Display $node;
}
if ($n == 10) {
echo 'Next';
}
You should use a regular for loop
if(count($nodes) < 10) {
$nnodes = count($nodes);
} else {
$nnodes = 10;
}
for($i = 0; $i < $nnodes; $i++) {
echo $nodes[$i];
}
I had the same problem, solved this way
<?php $i=0 ?>
<?php foreach ($nodes as $node) : ?>
<?php $i++ ?>
<?php echo "here is the output: ".$node."<br>\n"; ?>
<?php if ($i == 3) break; ?>
<?php endforeach; ?>
if ($n++ <= 9) {
echo 'what ever you like to get going';
}

Categories