This question already has answers here:
Loop a multidimensional array and only print two specific column values per row
(6 answers)
Closed 6 years ago.
Okay, I Have an array and I want to loop through it every time you press a button. And when the array has made it to its last number it starts on 0 again.
So it starts on 0, when I press the button it goes to 1 and when I press again it goes to 2. Lets say it has a lenght of three, so when I press again it should go back to 0...
I just don't know I can do that. Can someone help out? It would be hugely appreciated!
This is what I tried so far:
$foo = array('bar', 'baz');
$foo = 0;
$foo++;
update($foo);
Ofcourse is this not working because $foo becomes 0 each time the page reloads...
Yes this is quite simple. Just have a conditional statement that sets your loop variable back to 0 if it hits the length of the array. Here is some very basic pseudo code.
if(loopvariable = arrayLength){
set loopVariable = 0
}
Okay, I solved it.
I just put the variables in an session.
This is my code:
if(!isset($_SESSION['b']))
$_SESSION['b'] = 0;
$_SESSION['b'] += 1;
if($_SESSION['b'] > 4){
$_SESSION['b'] = 0;
}
Related
This question already has answers here:
Notice: Undefined index when trying to increment an associative array in PHP
(6 answers)
Closed 4 months ago.
I want to increment a value of an array, which is potentially not existing yet.
$array = [];
$array['nonExistentYet']++; // Notice
Problem
This leads to a NOTICE.
Attempt
I found a way to do this, but its kinda clunky:
$array = [];
$array['nonExistentYet'] = ($array['nonExistentYet'] ?? 0) + 1;
Question
Is there a more human readable/elegant way to do this?
well i guess a more readable way would be to use if..else as,
$arr = [];
if(array_key_exists('nonExistentYet', $arr)) {
$arr['nonExistentYet'] += 1;
}
else {
$arr['nonExistentYet'] = 1;
}
If this is used often, you can define a little helper method, which also uses an interesting side effect...
function inc(&$element) {
$element++;
}
$array = [];
inc($array['nonExistentYet']);
print_r($array);
gives...
Array
(
[nonExistentYet] => 1
)
with no warning.
As you can see the function defines the parameter as &$element, if this value doesn't exist, then it will be created, so the function call itself will create the element and then it will just increment it.
My standard implementation for this is:
if (isset($array['nonExistentYet']))
$array['nonExistentYet']++;
else
$array['nonExistentYet'] = 1;
But this is one of the rarely scenarios where I use the # operator to suppress warnings, but only if I have full control over the array:
#$array['nonExistentYet']++;
Generally, it is not good to suppress warnings or error messages!
What you ask is a little vague,
Either the variable exists and you increment it, or it does not exist in this case you create it.
In another case suppose that you want to do it in a for loop, in this case you do not have to worry about the existence of the variable.
One way is ternary operator, which checks if array value exists:
$array['iDoNotExistYet'] = empty($array['iDoNotExistYet']) ? 1 : ++$array['iDoNotExistYet'];
Other one would be just rewriting it to if and else condition.
This question already has answers here:
Notice: Undefined index when trying to increment an associative array in PHP
(6 answers)
Closed 4 months ago.
I have a foreach loop, inside of which I am building a big multi-dimensional array and doing lots of incriminating, like this:
$totalCosts['sawn']['materials'] += $sawnMaterialsCost;
On the first iteration of the loop, the key 'materials' is not set, so it throws an undefined index notice (not terrible, but annoying).
I can fix that by defining it before the loop like this:
$totalCosts['sawn']['materials'] = '0.00';
BUT, I have many keys I am filling by incrementing, and I don't like having to set each variable/key to '0' for every one before looping. Is there a better way to do this so the first iteration of the loop checks for a value and sets it to 1 if not found?
$totalCosts['sawn']['materials'] = ($totalCosts['sawn']['materials'] ?? 0) + $sawnMaterialsCost;
??, an operator introduced in PHP 7, uses the left-hand operand if defined and not null, otherwise the right-hand operand.
The performance cost of ?? is negligible, unless you are doing millions of comparisons. On an Amazon c3.medium, I measured each at ~250ns more than a static assignment. On a loop of 10,000,000 that's a half-second penalty.
perf.code.
Yes - first check if it exists, and if not, create it.
foreach($something as $key) { //e.g. $key = 'materials'
if (!isset($totalCosts['sawn'][$key])) $totalCosts['sawn'][$key] = 0;
$totalCosts['sawn'][$key] += $sawnMaterialsCost;
}
Well, I don't think there is a solution way more compact than this:
foreach(...) {
if(!isset($totalCosts['sawn'][$yourkey]))
$totalCosts['sawn'][$yourkey] = 0.00;
$totalCosts['sawn'][$yourkey]+=$sawnMaterialsCost;
}
Using the ternary operator is one way you can accomplish this.
$totalCosts['sawn']['materials'] = !empty($totalCosts['sawn']['materials']) ? $totalCosts['sawn']['materials'] + $sawnMaterialsCost : $sawnMaterialsCost;
This way you won't try adding to a non-existent value.
This question already has answers here:
The 3 different equals
(5 answers)
Closed 6 years ago.
I have a short shop form. You can buy there some pens, mugs etc.
After you put a number of items you want to buy I am trying to validate the input information and if it is not correct just change it into 0.
Looks like the !is_numeric function doesn't work, because it always makes the amount 0.
Any help please? Does ! work with this function at all?
$mugAmount = Input::get('mugAmount');
if(!isset($mugAmount) OR $mugAmount = NULL OR !is_numeric($mugAmount) OR $mugAmount < 0){
$mugAmount = 0;
};
It is because of this $mugAmount = NULL. This should be $mugAmount == NULL.
= and == means totally different things ;)
ps: besides you can remove this comparison to NULL because if it is NULL then !isset($mugAmount) will be true :)
This question already has answers here:
Passing arrays as url parameter
(11 answers)
Closed 9 years ago.
$deposit=$_POST['amountdeposit'];
$arr= array();
for($i=0;$i<10;$i++)
{
if($arr[$i]=='\0')
{ $arr[$i]= array("$deposit");
}
break;
}
$page= "step2.php?arr=$arr";
header("Location:$page");
?>
what i want to do is each time there's a change in $deposit , this value is stored in $arr[$i] and then it is passed in a url so that i could use GET on that step2.php page.
What I see is just arr=array instead of values :/ please help me.
You want http_query_string. It will do exactly what you want.
A couple of other comments have recommended http_query_string, however I would use serialize along with urlencode.
Replace:
$page= "step2.php?arr=$arr";
with:
$page= "step2.php?arr=" . urlencode(serialize($arr));
Then when you get to step2.php, unserialize(urldecode($_GET['arr'])) will contain your array as you originally built it.
This question already has answers here:
Remove item from array if it exists in a 'disallowed words' array
(2 answers)
Closed 4 months ago.
I have two arrays: $all_languages and $taken_languages. One contains all languages (like 200 or something), but second - languages that have been chosen before (from 0 to 200).
I need to remove all languages that have been taken ($taken_languages) from $all_languages and return new array - $available_languages.
My solution was two loops, but, first, it doesn't work as expected, second - it's 'not cool' and I believe that there are better solutions! Can you point me to the correct path?
This is what I have done before, but, as I said, it doesn't work as expected...
if (!empty($taken_languages)) {
foreach ($all_languages as $language) {
foreach ($taken_languages as $taken_language) {
if ($taken_language != $language) {
$available_languages[] = $language;
break;
}
}
}
} else {
$available_languages = $all_languages;
}
Thanks in advice!
PHP has a built in function for this (and just about everything else :P)
$available_languages = array_diff($all_languages, $taken_languages);
PHP Manual (array_diff)
The array_diff function will work for you.
http://php.net/manual/en/function.array-diff.php