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;
}
Related
Given this code (https://psalm.dev/r/156e52eb66):
<?php
function keys(): array
{
return ['foo', 'bar'];
}
// no lines above can be changed
foreach (keys() as $k) {
echo gettype($k);
}
how would one type it assuming the keys function is not under our control (in a different project) and it effectively returns an array of mixed (array<array-key, mixed>).
So, one may only change the loop and around it.
Is it even possible?
UPD: I reported https://github.com/vimeo/psalm/issues/2025
If I get it right this might help you:
foreach (array_keys(keys()) as $k) {
echo gettype(keys()[$k])."\n";
}
You could use for loop instead of foreach loop to fix the warning.
$keys = keys();
for( $i = 0; $i < count( $keys); $i++ ) {
echo gettype( $keys[$i] );
}
Here is the link in Psalm https://psalm.dev/r/20c1cbab73
It's a bug of psalm.
Refer to Github: INFO: MixedAssignment - Cannot assign to a mixed type | when using string array key #1281,
And it has been fixed by muglug in this commit 6033345694727d7c3cf84adc76507c3785ed0295
I need help regarding a foreach() loop. aCan I pass two variables into one foreach loop?
For example,
foreach($specs as $name, $material as $mat)
{
echo $name;
echo $mat;
}
Here, $specs and $material are nothing but an array in which I am storing some specification and material name and want to print them one by one. I am getting the following error after running:
Parse error: syntax error, unexpected ',', expecting ')' on foreach line.
In the Beginning, was the For Loop:
$n = sizeof($name);
for ($i=0; i < $n; $i++) {
echo $name[$i];
echo $mat[$i];
}
You can not have two arrays in a foreach loop like that, but you can use array_combine to combine an array and later just print it out:
$arraye = array_combine($name, $material);
foreach ($arraye as $k=> $a) {
echo $k. ' '. $a ;
}
Output:
first 112
second 332
But if any of the names don't have material then you must have an empty/null value in it, otherwise there is no way that you can sure which material belongs to which name. So I think you should have an array like:
$name = array('amy','john','morris','rahul');
$material = array('1w','4fr',null,'ff');
Now you can just
if (count($name) == count($material)) {
for ($i=0; $i < $count($name); $i++) {
echo $name[$i];
echo $material[$i];
}
Just FYI: If you want to have multiple arrays in foreach, you can use list:
foreach ($array as list($arr1, $arr2)) {...}
Though first you need to do this: $array = array($specs,$material)
<?php
$abc = array('first','second');
$add = array('112','332');
$array = array($abc,$add);
foreach ($array as list($arr1, $arr2)) {
echo $arr1;
echo $arr2;
}
The output will be:
first
second
112
332
And still I don't think it will serve your exact purpose, because it goes through the first array and then the second array.
You can use the MultipleIterator of SPL. It's a bit verbose for this simple use case, but works well with all edge cases:
$iterator = new MultipleIterator();
$iterator->attachIterator(new ArrayIterator($specs));
$iterator->attachIterator(new ArrayIterator($material));
foreach ($iterator as $current) {
$name = $current[0];
$mat = $current[1];
}
The default settings of the iterator are that it stops as soon as one of the arrays has no more elements and that you can access the current elements with a numeric key, in the order that the iterators have been attached ($current[0] and $current[1]).
Examples for the different settings can be found in the constructor documentation.
This is one of the ways to do this:
foreach ($specs as $k => $name) {
assert(isset($material[$k]));
$mat = $material[$k];
}
If you have ['foo', 'bar'] and [2 => 'mat1', 3 => 'mat2'] then this approach won't work but you can use array_values to discard keys first.
Another apprach would be (which is very close to what you wanted, in fact):
while ((list($name) = each($specs)) && (list($mat) = each($material))) {
}
This will terminate when one of them ends and will work if they are not indexed the same. However, if they are supposed to be indexed the same then perhaps the solution above is better. Hard to say in general.
Do it using a for loop...
Check it below:
<?php
$specs = array('a', 'b', 'c', 'd');
$material = array('x', 'y', 'z');
$count = count($specs) > count($material) ? count($specs) : count($material);
for ($i=0;$i<$count;$i++ )
{
if (isset($specs[$i]))
echo $specs[$i];
if (isset($material[$i]))
echo $material[$i];
}
?>
OUTPUT
axbyczd
Simply use a for loop. And inside that loop, extract values of your array:
For (I=0 to 100) {
Echo array1[i];
Echo array2[i]
}
I am trying to learn php, and I am playing around with while loops. I was wondering how to print out a specific number in an array in php. Fx:
$a = [1,3,5,7,9,11,13];
$s = 3;
while($a == 3) {
echo $s.' is in the row';
$a++;
}
In this example I would like to run through the $a and see if 3 exist there. If it does it has to echo '3 is in the row' I tried to make a while loop, but it is not correct. Can anyone see what I am doing wrong? Just to say it, I think it is very wrong, but I don't know how to solve it, if I have to use the while loop?
Best Regards
Mads
Your while condition reads: "While the value of $a equals 3", but $a is an array, so its value can't ever be 3. The loop will never be executed. In PHP, we would write:
if (in_array($s, $a))
echo $s, ' was found in the array';
Or, if you insist on writing loops:
foreach ($a as $key => $value)
{
if ($value == $s)
{
echo $s, ' was found at offset ', $key;
break;//end terminate loop
}
}
Of course, you could also write:
for ($i=0, $j=count($a);$i<$j;++$j)
{
if ($a[$i] == $s)
{//you could move this condition to the loop itself, even
echo $s, ' found in array at offset ', $i;
break;
}
}
You can, if you want use a while loop, too, but that wouldn't be the best choice for your particular case. Just read through the manual on php.net. There are many, many array_* functions available, and there are many ways to iterate over your data.
Another worry is your using the array name as a sort-of C-style pointer: $a++; in C, an pointer can be incremented to set it to point to the next value in an array (if the new memory address is valid, and the pointer is valid, and all of the other things you have to worry about in C). PHP does not work this way. An array isn't really an array: it's a hash map. incrementing an array, therefore, is pointless and most likely to be a bug. The for loop is the closest you can get to traversing an array using the ++ operator.
You're looking for in_array. This checks if a value exists in an array, in the form of:
in_array ( mixed $needle , array $haystack )
So, in your case, you'd want to do:
$a = [1,3,5,7,9,11,13];
$s = 3;
if (in_array($s, $a)) {
echo $s.' is in the row';
}
foreach($a as $b) {
if($b == 3)
echo $b.' is in the row';
}
Modify slightly your code changing while condition:
$a = array(1,3,5,7,9,11,13);
$s = 3;
$counter = 0;
while($counter < count($a)) {
if ( $a[$counter] == $s )
echo $s.' is in the row';
$counter++;
}
Added counter to iterate through while loop until end of array.
count() method returns number of items in array.
This solution prints all occurences of your number.
To have better code, change names of variables:
$numbers = array(1,3,5,7,9,11,13);
$target = 3;
$counter = 0;
while($counter < count($numbers)) {
if ( $numbers[$counter] == $target )
echo $target.' is in the row';
$counter++;
}
There are two ways to do it,
First, you can loop through all items in the array using a foreach() loop.
That way, you can go through them all and if you have multiple conditions, it makes your code a bit more readable.
And example of that loop is like this:
foreach($array as $array_item) {
if($array_item === 3) {
echo "3 is in the array";
}
}
The alternative is to use a built in function to find if something is in the array. THis is probably much faster, though I haven't benchmarked the difference.
if(in_array(3, $array)) {
echo "3 is in the array";
}
you can use
array_search ,in_array , and forearch or for loops to itertate through the array.
For learning purposes
$a = [1,3,5,7,9,11,13];
$s = 3;
for($i=0;$i<count($a);$i++)
{
if($a[$i]==$s){
echo $s.' is in the row';
}
}
of course in real life
if (in_array(3, $a)) {
// Do something
}
would be better;
<?php
$a = [1,3,5,7,9,11,13];
$s = 3;
for($a=0;$a < 20; $a++)
{
while($a == 3) {
echo $s.' is in the row';
//$a++;
}
}
?>
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.
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
}