I'm getting a very weird results when trying to loop through a comma delimited list in PHP.
It sometimes only outputs a few of them and there seems no logical reason to why it doesn't loop through all of them, and I can't for the life of me figure out what's actually causing it.
My code is:
//pids = &pids=1,2,3,6,7,9
$pids = $_GET['pids'];
$photoIdArray = explode(",", $pids);
for($i = 0; $i <= count($photoIdArray); $i++) {
foreach($photoIdArray as $j){
if($i == $j){
echo "{$j}";
}
}
}
// result = 1236
This is just for testing so there is im not checking the inputs to prevent exploits and what not at the moment.
Any help would be appreciated.
Thanks!
Combining 2 loop for and foreach is overkill for something like this
Try using only foreach
$pids = "1,2,3,6,7,9";
$photoIdArray = explode(",", $pids);
foreach($photoIdArray as $value)
{
echo $value;
}
Output
123679
It is because you are looping through your values and check if $i is the same as the value. You should check
if ($photoIdArray[$i] == $j) {
instead of
if ($i == $j) {
This is the reason it didn't work, but you should still use Baba's method.
I agree with Dusan, Baba & Co., but to answer the actual question:
Nothing weird happens here. i loops from 0 to 6 (though the array has only indices 0..5), and you compare i with the VALUES of the array, which range from 1 to 9. Of course, only the values 1 to 6 are matched, because i never exceeds 6.
EDIT: Asad and Sietse were faster.
Related
I can not figure out how to print all $_POST array items (ending in successive numbers) if one or more numbers do not exist. Not sure how to explain this... For example..
$i = 1;
while( isset($options['item_code'.$i]) )
{
echo $options['item_code'.$i];
$i++;
}
This code works fine as long as the numbers continue to exist in order...
item_code, item_code1, item_code2, item_code3, etc...
But once a number is removed, the if statement stops and the rest of the values are not printed. For example...
item_code, item_code1, item_code3, etc...
Will stop at "item_code1" because item_code2 does not exist.
I've tried solutions given to similar questions here on stackoverflow but they either do not work, do the same thing, or create a continuous loop.
I would appreciate any help that someone can give me here.
you are doing it in wrong way. Please update your code like this. replace $i<=4 with number of element you want to trace
$key = end(array_keys($options));
$dataa = explode('item_code',$key);
$count = $dataa[1];
$i = 1;
while( $i <= $count )
{
if(isset($options['item_code'.$i])){
echo $options['item_code'.$i];
}
$i++;
}
I guess it can be done with an array_filter and strpos functions:
<?php
$codes = array_filter($options, function ($key) {
return strpos($key, 'item_code') === 0;
}, ARRAY_FILTER_USE_KEY);
foreach ($codes as $code) {
echo $code . PHP_EOL;
}
Instead of while use foreach like
foreach($options as $option){
echo $value;
}
I'm noob in PHP programming and for my surprise I found it difficult to create an array using loop and to input in it values using arithmetic progression with +4 difference.I spent over an hour and tried a lot of code,searched so many examples.Below is my code that work(maybe) but not properly.
<?php
$array = [];
for($x=0;$x<10;$x++){
for($i=0;$i<100;$i+=4){
$array[] = $i;
}
break;
}
var_dump($array);
?>
I must have no more than 10(0-9 key) values,but because of $i the loop continues to 96 up to 24 keys.Maybe it's stupid question but I've totally blocked.
Is that what you want ?
<?php
$array = [];
for($x=0;$x<10;$x++){
$array[] = $x*4;
}
var_dump($array);
?>
Or maybe simpler
$array = range(0,36,4);
Doc for range : http://php.net/manual/fr/function.range.php
Then perhaps you have been overthinking this. You just need one loop, and can simply scale your key by 4:
foreach (range(0, 10) as $x) {
$array[] = 4 * $x;
}
Which will just add 0 for key 0, and 4 for key 1, and so on.
Note that for larger ranges, you should keep the classic for of course. It's more readable/obvious for math thingys anyway.
Use this:-
for ($x = 0; $x < 10; $x++) {
$array[$x] = $x * 4;
}
echo '<pre>';
print_r($array);
I think you must read basic of array here is a link that is useful for you link
I'm trying to print an array until it's empty.
Here is my code:
for ($i=0; $array[0][$i]!=NULL; ++$i){
echo $array[0][$i];
}
However it looks like it performs the echo one extra time, I don't know why ?
Here's my output for an array that contains data up to array[0][2].
I am sure that array[0][3] is empty, I tried it with if(array[0][3]==NULL)
Test 0
Test 1
Test 2
( ! ) Notice: Undefined offset: 3 in C:\... on line 9
Any idea ?
You should use the arrays length when you loop... Or try this instead:
foreach($array[0] as $val) {
echo $val;
}
It makes perfect sense, really. PHP can not magically know that the next id (in your example, index number '3') is not set, it has to access the variable to determine that. That's also why you get the notice.
In short, it does not execute the body of the for loop, but it has to execute the test to determine whether or not to continue.
Anyway, use a foreach loop, or calculate the number of items in the array first and increment $i till they match.
Possible alternatives to you code that should actually work.
foreach($array[0] as $val)
if($val===null)
break;
else
echo $val;
or
$arrlen=count($array[0]);
for($i=0;$i<$arrlen;$i++)
if($array[0][$i]===null)
break;
else
echo $array[0][$i];
or even
$i=0;
while($array[0][$i]!==null) { //not recommended, can cause infinite loop
echo $array[0][$i];
$i++;
}
The reason why it's throwing an error is because an array index that does not exist is not equal to NULL. You can modify your code to this:
for ($i=0; isset($array[0][$i]); ++$i){
echo $array[0][$i];
}
Or try this instead:
$ctr = count($array[0]);
for ($i = 0; $i < $ctr; $i++) {
echo $array[0][$i];
}
The loop should finish after reaching the end of the array.
I'm creating a program which goes through data in a array and filter outs any repeats within it and then echos out anything which isn't a repeated piece of data
for ($i = 0; $i < count($urlArray); $i++) {
for ($j = 0; $j < count($urlArray); $j++) {
if($i != $j)
{
if($urlArray[$i] !== $urlArray[$j])
echo $urlArray[$i];
}
}
}
I'm fairly certain there's something wrong but I can't quite spot it, any help with this would be great.
I dont get, how your array is structured, but whats about just array_unique()
$urlArray = array_unique($urlArray);
Or in your case (because you want to echo it
foreach (array_unique($urlArray) as $url) echo $url;
Update:
Sorry, just mixed up two functions :) Of course its array_unique() and not array_filter().
You could use built in function array_unique() to remove duplicate values in array
$result = array_unique($urlArray);
print_r($result);
In web development, I often find I need to format and print various arrays of data, and separate these blocks of data in some manner. In other words, I need to be able to insert code between each loop, without said code being inserted before the first entry or after the last one. The most elegant way I've found to accomplish this is as follows:
function echoWithBreaks($array){
for($i=0; $i<count($array); $i++){
//Echo an item
if($i<count($array)-1){
//Echo "between code"
}
}
}
Unfortunately, there's no way that I can see to implement this solution with foreach instead of for. Does anyone know of a more elegant solution that will work with foreach?
I think you're looking for the implode function.
Then just echo the imploded string.
The only more elegant i can think of making that exact algorithm is this:
function implodeEcho($array, $joinValue)
{
foreach($array as $i => $val)
{
if ($i != 0) echo $joinValue;
echo $val;
}
}
This of course assumes $array only is indexed by integers and not by keys.
Unfortunately, I don't think there is any way to do that with foreach. This is a problem in many languages.
I typically solve this one of two ways:
The way you mention above, except with $i > 0 rather than $i < count($array) - 1.
Using join or implode.
A trick I use sometimes:
function echoWithBreaks($array){
$prefix = '';
foreach($array as $item){
echo $prefix;
//Echo item
$prefix = '<between code>';
}
}
If more elaborate code then an implode could handle I'd use a simple boolean:
$looped = false;
foreach($arr as $var){
if($looped){
//do between
}
$looped = true;
//do something with $var
}