Here code (executed in php 5.3.5 and 5.2.13):
$res = array(1, 2, 3);
unset($res[0]);
for($i = 0; $i < sizeof($res); $i++)
{
echo $res[$i] . '<br />';
}
In results i see
<br />2<br />
Why only one element, and first empty? Can`t understand. When doing:
print_r($res);
See:
Array ( [1] => 2 [2] => 3 )
Thanx for help!
This is because you start with $i = 0; rather than 1 which is the new first index. The last element is missing because it stops before the second (previously third) element since the size has been reduced to 2. This should get the results you wish:
foreach($res as $value) {
echo $value . '<br />';
}
PHP doesn't rearrange the keys on unset. Your keys after the unset are 1 and 2. In the for cycle, i gets the 0 and 1 values. Using this snippet you should init i to 1, the first key of the array.
Hint 1: Use foreach to itearate over an array.
Hint 2: Don't use aliases. Use count instad of sizeof.
Because after unset sizeof array = 2
And basicly use error_reporting(E_ALL) for development, it will help you
This is not working as expected because when you unset, so sizeof() returns 2. Thus you are looping on 0 to less than 2(aka 1).
So it will only display the element at index 1, because you unset element at 0.
A simple fix for this would be to use the foreach loop:
foreach($res as $value){
echo $value .'<br />';
}
It is iterating 2 times, the first time through it is accessing index 0, which you've unset, the second time it's accessing index 1, which is what you see outputted. Even though there are only two elements, at index 1 & 2, you're still starting from the original index.
Related
I use PHP/7.2.0beta3. So I want to create a custom function to reverse an array in PHP. If the array is (1,2,3) the functions turns it to (3,2,1).
I thought I should use the array_pop, grab the last value of the array and pass it to another array.
The problem
Here is the code I wrote. Just copy it and run it as PHP. I dont know why it stops in the middle of the array and does not continue till the end.
$originalarray = range(0, 100, 5);//works
echo '<br> original array <br>';
print_r($originalarray); // 0-100, with 5 step
function customreverse($x){
echo '<br> original array in function <br>';
print_r($x); //works, 0-100, with 5 step
echo '<br> sizeof in function '.sizeof($x).'<br>'; //works, is 21
for($a=0; $a<sizeof($x); $a++){
$reversearray[$a] = array_pop($x);
echo '<br> reversearray in for loop <br>';
print_r($reversearray);//stops at 50
echo '<br> a in for loop <br>';
echo $a;//stops at 10
}
echo '<br> reverse in function <br>';
print_r($reversearray);////stops at 50
}
customreverse($originalarray);
The same problem occurs even if I replace sizeof with count. Or $a<sizeof($x) with $a<=sizeof($x). Why does it stop and does not traverse the whole array? What am I missing here?
Thanks
sizeof (or count) is evaluated on every iteration of the loop and the array shrinks on each iteration. You need to store the original count in a variable. For Example (I removed a few lines to focus on the issue):
<?php
$originalarray = range(0, 100, 5);//works
function customreverse($x){
$origSize=sizeof($x);
for($a=0; $a<$origSize; $a++){
$reversearray[$a] = array_pop($x);
}
return($reversearray);//stops at 50 (Now it doesn't)
}
print_r(customreverse($originalarray));
jh1711 properly explained that your loop ends early because the middle statement in for(statement1; statement2; statement3) gets executed each iteration, and because you're popping the original array within the loop, sizeOf() returns a smaller number each time.
You could compact your code a bit, by building your reverse array like so:
while(!empty($original)) $reverse[] = array_pop($original);
If you want to preserve key=>value bindings (meaning reverse keys as well, so that the same keys will bind to the same values), you could do:
while(!empty($original)):
$val = end($original); // set pointer at end of array
$reverse[key($original)] = $val;
endwhile;
If you want to modify the array in-place (not create a 2nd array), you could do:
for($i=0, $j=sizeof($original); $i < $j; $i++){
array_splice($original,$i,0,array_pop($original));
} // pop last element and insert it earlier in the array
I have a foreach loop like below code :
foreach($coupons as $k=>$c ){
//...
}
now, I would like to fetch two values in every loop .
for example :
first loop: 0,1
second loop: 2,3
third loop: 4,5
how can I do ?
Split array into chunks of size 2:
$chunks = array_chunk($coupons, 2);
foreach ($chunks as $chunk) {
if (2 == sizeof($chunk)) {
echo $chunk[0] . ',' . $chunk[1];
} else {
// if last chunk contains one element
echo $chunk[0];
}
}
If you want to preserve keys - use third parameter as true:
$chunks = array_chunk($coupons, 2, true);
print_r($chunks);
Why you don't use for loop like this :
$length = count($collection);
for($i = 0; $i < $length ; i+=2)
{
// Do something
}
First, I'm making the assumption you are not using PHP 7.
It is possible to do this however, it is highly, highly discouraged and will likely result in unexpected behavior within the loop. Writing a standard for-loop as suggested by #Rizier123 would be better.
Assuming you really want to do this, here's how:
Within any loop, PHP keeps an internal pointer to the iterable. You can change this pointer.
foreach($coupons as $k=>$c ){
// $k represents the current element
next($coupons); // move the internal array pointer by 1 space
$nextK = current($coupons);
prev($coupons);
}
For more details, look at the docs for the internal array pointer.
Again, as per the docs for foreach (emphasis mine):
Note: In PHP 5, when foreach first starts executing, the internal array pointer is automatically reset to the first element of the
array. This means that you do not need to call reset() before a
foreach loop. As foreach relies on the internal array pointer in PHP
5, changing it within the loop may lead to unexpected behavior. In PHP
7, foreach does not use the internal array pointer.
Let's assume your array is something like $a below:
$a = [
"a"=>1,
"b"=>2,
"c"=>3,
"d"=>4,
"e"=>5,
"f"=>6,
"g"=>7,
"h"=>8,
"i"=>9
];
$b = array_chunk($a,2,true);
foreach ($b as $key=>$value) {
echo implode(',',$value) . '<br>';
}
First we split array into chunks (the parameter true preserves the keys) and then we do a foreach loop. Thanks to the use of implode(), you do not need a conditional statement.
well this'd be 1 way of doing it:
$keys=array_keys($coupons);
for($i=0;$i<count($keys);++$i){
$current=$coupons[$keys[$i]];
$next=(isset($keys[$i+1])?$coupons[$keys[$i+1]]:NULL);
}
now the current value is in $current and the next value is in $next and the current key is in $keys[$i] and the next key is in $keys[$i+1] , and so on.
I'm trying to run a PHP script that finds all the numbers divisible by 3 or 5, dumps them into an array, and adds all the values together. However, When I try to run it, I get a number output (I don't know if it's correct or not) and several hundred errors. They start out with:
Notice: Undefined offset: 1 in G:\Computer Stuff\WampServer\wamp\www\findthreesandfives.php on line 18
Then the offset number increases by increments of 1-3 (randomly, I haven't seen a pattern yet). I can't figure out what's wrong. Here's my code:
<?php
function loop($x)
{
$a = array(); //array of values divisible by 3 or 5
$l = 0; //length of the array
$e = 0; //sum of all the values in the array
for ($i=0; $i<=$x; $i++){ //this for loop creates the array
$n3=$i%3;
$n5=$i%5;
if($n3 === 0 || $n5 === 0){
$a[$i]=$i;
$l++;
}
}
for ($v=0; $v<=$l; $v++){ //this loop adds each value of the array to the total value
$e=$e + $a[$v];
}
return $e;
}
echo loop(1000);
?>
Someone please help...
The problem in your code is the following line:
$a[$i]=$i;
Should be:
$a[count($a)] = $i;
This is because the value of $i is always increasing, so using $i as your pointer will create gaps in the array's indices. count($a) returns the total number of items in the given array, which also happens to be the next index.
EDIT: #pebbl suggested using $a[] = $i; as a simpler alternative providing the same functionality.
EDIT 2: Solving the subsequent problem the OP described in the comments:
The problem seems to be that $l is greater than the number of items in $a. Thus, using count($a) in the for loop should fix your subsequent error.
Try replacing:
for ($v=0; $v<=$l; $v++){
With:
for ($v=0; $v<=count($a); $v++){
I found the same problem as #zsnow said. There are gaps within $a. The if condition allowed the gaps making the assignment skip some indexes. You can also use this
foreach ($a as $v){ //this loop adds each value of the array to the total value
$e=$e + $a[$v];
}
should actually be
foreach ($a as $v){ //this loop adds each value of the array to the total value
$e=$e + $v;
}
Lets say i have an array in PHP
$test['michael_unique_id'] = 3;
$test['john_unique_id'] = 8;
$test['mary_unique_id'] = 10;
.
.
.
.
$test['jimmy_unique_id'] = 4;
(the values (3,8,10.........4) are unique)
Lets say i want to search for the unique id 10, and get the order of the matching element in the array. In this example, the third element has the value 10, so i should get the number 3.
I can do it by scanning with a for loop looking for the value i'm searching and then get the $i value when i have a match, but i wonder if there is any built-in function (or a better method) that implements this.
You can get all of the array's values as an array with array_values() and then use array_search() to get the position (offset) of that value in the array.
$uniq_id = 10;
$all_vals = array_values($test); // => array(3, 8, 10, ... )
echo array_search( $uniq_id, $all_vals ); // => 2
Because PHP array indices are zero-based, you'll get 0 for the first item, 1 for the second item, etc. If you want the first item to be "1," then just add one. All together now:
$uniq_id = 10;
echo array_search( $uniq_id, array_values( $test ) ) + 1; // => 3
It's not clear to me, however, that this is necessarily as performant as just doing a foreach:
$uniq_id = 10;
$idx = 1;
foreach($test as $val) {
if($val == $uniq_id) {
break;
}
$idx++;
}
echo $idx; // => 3
Well, array_search will give you the key, but in your case, you want the index of that key, so I believe a loop is your best bet. Is there a good reason why you need the index? It doesn't seem very useful to me.
I have a multi-dimensional array like
Array
(
[0] => Array
(
[ename] => willy
[due_date] => 12:04:2011
[flag_code] => 0
)
[1] => Array
(
[Father] => Thomas
[due_date] => 13:04:2011
[flag_code] => 0
)
[2] => Array
(
[charges] => $49.00
)
)
i want to display values of array using php. but still fail. please any one help me to do this task....?
Since you're so adamant that this be accomplished using only for loops, I have to assume this is a homework question. Because of this, I'll point you to several PHP manual pages in the hopes that you'll review them and try to learn something for yourself:
Arrays
For Loops
Foreach Loops
Now, I'm going to break your actual question a few different questions:
Is it possible to display a multidimensional array using for loops?
Yes. It's entirely possible to use a for loop to iterate over a multidimensional array. You simply have to nest for loops inside for loops. i.e. you create a for loop to iterate over the outer array, then inside that loop you use another for loop to iterate over the inner array.
How can I iterate over a multidimensional array using a for loop?
Generally, when you use a for loop, the loop will look something like this:
for($i = 0; $i < $maxValue; $i++) {
// do something with $1
}
While this works well for indexed arrays (i.e. arrays with numeric keys), so long as they have sequential keys (i.e. keys which use each integer in order. for example, an array with keys 0, 1, and 2 is sequential; an array with keys 0, 2, and 3 is not because it jumps over 1), this doesn't work well for associative arrays (i.e arrays with text as keys - for example, $array = array("abc" = 123);) because these arrays won't have keys with the numerical indexes your for loop will produce.
Instead, you need to get a bit creative.
One way that you could do this is to use array_keys to get an indexed array of the keys your other array uses. For example, look at this simple, one-dimensional array:
$dinner = array(
"drink" => "water",
"meat" => "chicken",
"vegetable" => "corn"
);
This array has three elements, each with an associative key. We can get an indexed array of its keys using array_keys:
$keys = array_keys($dinner);
This will return the following:
Array
(
[0] => drink
[1] => meat
[2] => vegetable
)
Now, we can iterate over the keys, and use their values to access the associative keys in the original array:
for($i = 0; $i < count($keys); $i++) {
echo $dinner[$keys[$i]] . "";
}
As we iterate over this loop, the index $i will be set to hold each index of the $keys array. The associated element of this key will be the name of a key in the $dinner array. We then use this key name to access the $dinner array elements in order.
Alternatively, you could use a combination of the reset, current and next functions to iterate over the values in the array, for example:
for($element = current($dinner);
current($dinner) !== false;
$element = next($dinner)
) {
echo $element . "<br />";
}
In this loop, you initialize the $element variable to be the first element in the array using reset, which sets the array pointer to the first element, then returns that element. Next, we check the value of current($dinner) to ensure that there is a value to process. current() returns the value of the element the array pointer is currently set at, or false if there is no element there. Finally, at the end of the loop, we use next to set the array pointer ahead by one. next will return false when we try to read beyond the end of the array, but we ignore that and wait for current to notice that there is no current element to stop the loop.
Now, having written all of that, there really isn't any reason to do jump through all these hoops, since PHP has the built-in foreach construct which allows you to iterate over each of an arrays elements, regardless of key type:
foreach($dinner as $key => $value) {
echo "The element in key '" . $key . "' is '" . $value ."'. <br />";
}
This is why I'm assuming this is a homework assignment, since you would probably never have reason to jump through these hoops in a production environment. It is, however, good to know that such constructs exist. For example, if you could use any loop but a foreach, then it would be a lot simpler to just use a while loop than to try to bash a for loop into doing what you want:
reset($dinner);
while (list($key, $value) = each($dinner)) {
echo "The value of '" . $key . "' is '" . $value . "'.<br />";
}
In summary, to iterate over a multidimensional array with associative keys, you would need to nest loops inside each other as shown in the answer to the first question, using one of the loops shown in the answer to the second question to iterate over the associative key values. I'll leave the actual implementation as an exercise for the reader.
To print the values of a array, you can use the print_r function:
print_r($array);
This saves a for-loop.
Just use the handy function print_r
print_r($myarray);
If you don't want to use the print_r function, then for a true n-dimensional array solution:
function array_out($key, $value, $n) {
// Optional Indentation
for($i=0; $i < $n; $i++)
echo(" ");
if(!is_array($value)) {
echo($key . " => " . $value . "<br/>");
} else {
echo($key . " => <br/>");
foreach($value as $k => $v)
array_out($k, $v, $n+1);
}
}
array_out("MyArray", $myArray, 0);
Not sure if its possible to do with a for loop and mixed associative arrays, but foreach does work just fine.
If you have to do it with a for loop, you want the following:
$count = count($array)
for($i = 0; $i <= $count; $i++)
{
$count2=count($array[$i]);
for($j = 0; $j <= $count2; $j++)
{
print $array[$i][$j] . "<br/>";
}
}
foreach( $array as $row ) {
$values = array_values($row);
foreach( $values as $v ) {
echo "$v<br>";
}
}
Should output:
willy
12:04:2011
0
Thomas
13:04:2011
0
$49.00
This will actually be readable:
echo '<pre>';
print_r($myCoolArray);
echo '</pre>';
You would need to do it using something like assigning array_keys to an array, then using a for loop to go through that, etc...
But this is exactly why we have foreach - it would be quicker to write, read and run. Can you explain why it must be done with for?