Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am currently working on a php project where I am trying to loop through an array using a foreach. However, sometimes the array may only contain 1 item so when I try and do a foreach it fails as 1 item is just seen as a normal variable.
Is there a way that I can trick php into thinking that a 1 item array is actually an array and not just a variable so that I don't get this error.
Thanks for your help.
foreach will work fine with arrays of size 0,1 or bigger. I suspect your problem is, that the variable doesn't really contain an array, but some scalar value - in this case use something like
if (!is_array($var)) $var=array($var);
foreach ($var as $item) {
//...
}
if(is_array($arr))
$arr2=$arr
else
$arr2=array($arr)
and then you iterate over $arr2
I would recommend just using a standard for loop. It should work no matter what the length of the array is
for($i = 0, $l = count($myArray); $i < $l; $i+=1){
//code in here
}
But chances are you have an issue with your array to begin. Posting the structure would be helpful, or you should var_dump it to make sure it is indeed an array.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
$vaccinesArr=array("0","0","0","0","0","0","0","0","0","0","0");
for($i = 0; $i < 11 ; $i++){
while($row = mysqli_fetch_assoc($result)){
if ($row['vaccID']== $i){
$vaccineArr[$i]++;
}
}
}
This is the part of my code, I need to increment according to this condition but I keep on getting syntax error, I searched but all the results I find are using foreach and incrementing all the indexes of the array while here I want to increment only one specific index. Can anyone help?
Your code will only work on the first iteration of the for loop, because when the inner while loop finishes there won't be any more rows to fetch from the query. You could rewind the query, but a better way to do it would be without the for loop.
while ($row = mysqli_fetch_assoc($result)) {
$vaccinesArr[$row['vaccID']]++;
}
Also, if the elements of $vaccinesArr are supposed to be numbers, you shouldn't put them in quotes. PHP will convert the strings to numbers when you use ++, but why be confusing?
$vaccinesArr = array(0, 0, 0, ....);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Generally we add to an array with
$myarray[] = $myItem
but if $myItem is a massive object I don't want it to get copied, instead I want it to be assigned by reference. Something like
$myarray[] = &$myItem
but that doesn't work and instead replaces every element in $myarray with $myItem
I tried
$myarray[count($myarray)] = &$myItem
but it still replaces everything in $myarray
I am running PHP v5.5
Objects are always assigned by reference. So:
$collection = array();
$blah = new Blah();
$blah->param = "something";
$collection[] = $blah;
$blah->param = "changed";
echo $collection[0]->param; // will output "changed"
According to How to push a copy of an object into array in PHP
Objects are always passed by reference in php 5 or later.
Therefore this question isn't really a concern anymore.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have the following array in PHP:
$item_array = array("facebook/1377445751.jpg_t","twitter/1377446022.gif_s","flickr/1377531219.png_w","flickr/1377531219.jpg_t_w");
I am iterating through this array, removing values that don't match the following regex:
(facebook|twitter|flickr)\/(\d{10})\.(jpg|png|gif)_(t_w|t|s|w)
Here is my code:
foreach($item_array as $key => $item) {
if(!preg_match('/(facebook|twitter|flickr)\/(\d{10})\.(jpg|png|gif)_(t_w|t|s|w)/', $item)) {
unset($item_array[$key]);
}
}
However, when I then use var_dump() on $item_array, I obtain an empty array. Since the preg_match doesn't match any of the array values, I'm under the impression that the problem lies there, even though I've tested it multiple times with RegExr.
Any ideas on where I might be going wrong?
As you can see here (click), your regex works fine. Perhaps you are having an issue you have not stated that deals with using the result.
I suspect that you might be looking for the $matches parameter, which will store your results.
Use like so:
preg_match('/(facebook|twitter|flickr)\/(\d{10})\.(jpg|png|gif)_(t_w|t|s|w)/', $item, $matches);
var_dump($matches);
This is all working perfectly as you described. I cleaned it up a little bit, but the code is the same. You must have a different problem.
$item_array = [
"facebook/1377445751.jpg_t",
"twitter/1377446022.gif_s",
"flickr/1377531219.png_w",
"flickr/1377531219.jpg_t_w",
"other stuff that won't match!"
];
foreach($item_array as $key => $item) {
$foo = preg_match('/(facebook|twitter|flickr)\/(\d{10})\.(jpg|png|gif)_(t_w|t|s|w)/', $item);
if(!$foo) {
echo $item; //displays "other stuff that won't match"
unset($item_array[$key]);
}
}
var_dump($item_array); //non match is removed
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Ok as per your suggestion I updated... By default Laravel returns JSON... I have set it to return an array but I am still getting the same row duplicated using:
$limits = array();
foreach($pieces as $coverage_limit){
$limits[] = coveragelimit::index($coverage_limit);
}
return json_encode($limits);
}
You're just overwriting $limits inside that foreach() loop. Perhaps you mean something more like
foreach($pieces as $coverage_limit){
$limits[] = coveragelimit::index($coverage_limit);
^^--- array push?
}
As well, you don't "implement" JSON instead of arrays. You work with NATIVE data structures, then encode that structure into JSON. JSON's a transport format, it's not something you should ever deal with natively.
the $limits array will hold the last value what coveragelimit::index() returns over the iterate, I would suggest a check on coveragelimit::index() return value if it falls with "Marc B"'s answer.
EDIT:
foreach($pieces as $key=>$coverage_limit) {
$limits[$key] = coveragelimit::index($coverage_limit);
}
or
foreach($pieces as $coverage_limit) {
array_push($limits, coveragelimit::index($coverage_limit));
}
both should returns the same as Marc B's answer
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is there any way of looping through an array and return each result as it is calculated, rather than waiting until all values are calculated before they are all displayed?
Say I have an array with numbers from 1 to 10 in it, is it possible to loop through the array and return 1, then 2, then 3, then 4, then 5, etc. instead of returning 12345678910 all in one go? Obviously I have simplified this request, but basically my loop calls a function that has a 1 second timeout, so for the user to wait 10+ seconds for all results to be returned rather than a result being returned each second is far less annoying.
Yes, new PHP 5.5 provides such a thing as generators.
function one_to_ten() {
for ($i = 1; $i <= 10; $i++) {
yield $i; //It is like a return, but can be done several times.
}
}
$generator = one_to_ten(); //The loop is not executed yet. We just created the generator.
/* Some big code here */
foreach ($generator as $number){//Only here the iteration starts.
echo "{$number} <br/>" ;
}