There is $sFactorGrades which I need to retrieve the 0th element from based on the GradeID and the CommutatorID, which is the 1st and 2nd element in the array respectively.
The GradeID and the CommutatorID is passed as parameters to the function.
The code that I have written is not returning the value which I know is present.
Any recommendations are welcome.
Here is my code:
function getMaximumSFactor($commuatorID, $gradeID) {
$sFactorGrades = populateSFactorGrades();
$arraySize = count($sFactorGrades);
for ($i = 0; $i < $arraySize; $i++) {
if (intval($sFactorGrades[i][1]) == $commuatorID && intval($sFactorGrades[i][2]) == $gradeID) {
return $sFactorGrades[i][0];
} else {
return 0;
}
}
}
Here is my data:
Array (
[0] => Array (
[0] => Maximum S Factor
[1] => Commutator ID
[2] => Grade ID
)
[1] => Array (
[0] => 0.6
[1] => 1
[2] => 2
)
[2] => Array (
[0] => 0.6
[1] => 1
[2] => 3
)
[3] => Array (
[0] => 0.6
[1] => 1
[2] => 4
)
)
Here is my result:
0
I suspect the reason for your loop always returning 0 is that you're passing i as the incrementing variable, and not the correct one: $i. Typos can be devastating... If it still doesn't work, feel free to update your post.
Edit: A tip is to insert this at the top of your page while in development stage:
ini_set('display_errors','On');
error_reporting(E_ALL);
In this case, it should give an undefined index error or similar.
The problem with your code is that you return too early. When your code encounters a return statement, it stops the iteration. You need to move the return statement outside the loop to prevent this from happening.
function getMaximumSFactor($commuatorID, $gradeID) {
$sFactorGrades = populateSFactorGrades();
$arraySize = count($sFactorGrades);
for ($i = 0; $i < $arraySize; $i++) {
if (intval($sFactorGrades[$i][1]) == $commuatorID &&
intval($sFactorGrades[$i][2]) == $gradeID) {
return $sFactorGrades[$i][0];
}
}
return 0;
}
If your code reached the last return, then it means that the if condition was never satisfied. For getMaximumSFactor (1, 2), this should return 0.2.
Demo
$sFactorGrades[i] need to be $sFactorGrades[$i].
Also it worth to use foreach() instead of normal for().
But thats not all. You need to check all values in array before returning result:
function getMaximumSFactor($commuatorID, $gradeID) {
$sFactorGrades = populateSFactorGrades();
foreach($sFactorGrades as $key=>$value){
if (intval($value[1]) == $commuatorID && intval($value[2]) == $gradeID) {
return $value[0];
}
}
return 0;
}
Related
i need to check if there is the name john more than 3 times in the names key within the following array that contains 4 different sub arrays
Array
(
[0] => Array
(
[total] => 4.2
[name] => john
)
[1] => Array
(
[total] => 2
[name] => john
)
[2] => Array
(
[total] => 3
[name] => adam
)
[3] => Array
(
[total] => 1.5
[name] => john
)
)
i was using mysql first but i prefer to use php instead
You can do the following:
$counts = array_count_values(array_column($array,"name"));
Then to check if there's 3 people called "john" :
if (isset($counts["john"]) && $counts["john"] >= 3) {
//Do stuff
} else {
//Do different stuff
}
To find check all peole not called "john" you can either change the above to as #Andreas suggests:
if (isset($counts["john"]) && (count($array) - $counts["john"]) > 3) {
//Do stuff
} else {
//Do different stuff
}
Alternatively do:
$notJohn = count(array_filter($array, function ($element) {
return $element["name" != "john";
}));
if ($notJohn >= 3) ...
A function like this will do the work
I have roughly written it in mobile.
$occurence = 0;
function a() {
for($x = 0; $x < 4; $x++) {
for($y = 0; $y < 2; $y++) {
if (array[$x][$y] === "John") {
$occurence++;
}
}
}
if($occurence > 3) {
return false;
}
else {
return true;
}
}
Here, $namesArray in an array with repeated value in it.Target is to count how many time exist each value in array.
$namesArray =
array("John","Mark","John","Dan","Hasib","Milon","Samad","Milon","John");
$newArray = array();
foreach($namesArray as $name){
if(isset($newArray[$name])){
$newArray[$name]++;
}else{
$newArray[$name] = 1;
}
}
According to code here is output :
Array(
[John] => 3
[Mark] => 1
[Dan] => 1
[Hasib] => 1
[Milon] => 2
[Samad] => 1
)
I am developing a Bio-metric election system but i am facing problem regarding election results.
I got this array after executing a query.
Array
(
[paty1] => Array
(
[NA122] => stdClass Object
(
[count] => 2
)
[NA2] => stdClass Object
(
[count] => 0
)
[NA56] => stdClass Object
(
[count] => 1
)
)
[party2] => Array
(
[NA122] => stdClass Object
(
[count] => 0
)
[NA2] => stdClass Object
(
[count] => 0
)
[NA56] => stdClass Object
(
[count] => 0
)
)
)
This array is stored in $data and it can have unlimited indexes.
Now if count of [Paty1][NA122] is greater then count of [Party2][NA122] so i will declare Party1 win in NA122 and i have to compare it with n number of indexes.
e.g. there is another index pary3 so firstly I will compare count of [party1][NA122] with [party2][NA122] and then with [party3][NA122] and winner will be the one with greater count . Can you please help me??
Thanks in advance
Try this:
foreach(current($Result) as $Const=>$val){
echo "Winner of Constituency '$Const': ". findWinner($Const,$Result).PHP_EOL;
}
function findWinner($Const, $Result){
$Max = 0;
$Winner = '';
foreach($Result as $Party => $ConstList){
if($ConstList[$Const]->count>$Max){
$Max = $ConstList[$Const]->count;
$Winner = $Party;
}
}
return $Winner;
}
Check live code here:
https://www.tehplayground.com/x5sPu7JxuexOdwU8
So you want to get the party with the max count for a given NA#.
You can use a function like this:
function maxParty($data, $na) {
$max = null;
foreach($data as $party => $values) {
if(is_null($max)) {
$max = $party;
continue;
} else {
if($values[$na]->count > $data[$max][$na]->count) {
$max = $party;
}
}
}
return $max;
}
Then you feed this function with a $data array and the NA# you want to calculate the max party with. For example
$winner = maxParty($data, 'NA122');
It will return the key for the winner party. I.e. "party1"
Do you mean something like this:
<?php
$data=getData();
$maxValue;
$maxKey;
foreach($data as $key => $paty)
if(!isset($maxValue) || $paty->count>$maxValue){
$maxValue=$paty->count;
$maxKey=$key;
}
echo "$maxValue $maxKey";
function getData(){
$a=array();
for($i=1;$i<100;$i++)
$a["paty$i"]=(object) array("count"=>$i);
return $a;
}
?>
Explanation:
getData returns an array like the one you described
foreach($data as $key => $paty) - iterates through the entire array
if ( ) -- checks if the current value is greater than the previous max
If you want to know more about PHP:
foreach, objects, arrays and google
I have a form like this
for($x=0;$x<8;$x++){
echo "<input name='test[]'> <br>";
}
then i'm input, and i get this result
Array
(
[0] => 1
[1] => 2
[2] => 0
[3] => 0
[4] => 0
[5] =>
[6] => 0
[7] =>
)
I want to sum then divide it. I'm using array_sum to sum it. Now the problem, how can i divide it depends on my input(s) not the many of input field(s) and i don't want count the zero as input.
so it will become something like this
(1+2) / 2
how can i achieve that? sorry for my bad english.
If you want only non-zero values to be counted, you'll need to filter those zero and empty values away. You can still use array_sum(), to sum the array, but you'll need a filter on your count(), because count() will count all elements, regardless of the content (except null-values).
array_filter() takes care of this. So you'll simply need this
echo array_sum($myArray) / count(array_filter($myArray)); // Outputs 1.5 with your sample-array
Live demo
http://php.net/count
http://php.net/array_filter
Try This:
$myArray = Array
(
[0] => 1
[1] => 2
[2] => 0
[3] => 0
[4] => 0
[5] =>
[6] => 0
[7] =>
)
$countArray = 0;
foreach($myArray as $v){
if($v !== 0 || $v !== ''){ //skip if 0 or empty
$countArray++
}
}
$result = array_sum($myArray) / $countArray;
You may use this PHP custom Function
<?php
/* Function for check and remove blank and empty element from array */
function remove_blank($arra)
{
$newArr = array();
$total = count($arra);
for($i = 0; $i <= $total; $i++)
{
if($arra[$i] != "" && $arra[$i] >= 0)
{
$newArr[] = $arra[$i];
}
}
echo "<pre>";
print_r($newArr);
}
$arra = array(1, 2, 0, 0,'', 0,'');
remove_blank($arra);
?>
OK so here's my code to edit a specific entry within the array, and the array layout is below.
$counter = 0;
foreach($_SESSION['cart'] as $listitem){
if ($listitem[0] == $_POST['product']){
if ($listitem[1] <= $_POST['remove']){
$remove = array($listitem[0], 0);
$_SESSION['cart'][$counter] = $remove;
} else {
$result = $listitem[1] - $_POST['remove'];
$remove = array($listitem[0], $result);
$_SESSION['cart'][$counter] = $remove;
}
}
$counter = $counter++;
}
Here's my $_SESSION['Cart'] Array layout
Array(
- [0] => Array ( [0] => 8 [1] => 0 )
- [1] => Array ( [0] => 10 [1] => 0 )
- [2] => Array ( [0] => 8 [1] => 1 )
)
Either my understanding of the array is wrong with this line of code:
$_SESSION['cart'][$counter]
Or my counter will not count:
$counter = $counter++;
since the only value it keeps editing the first entry [0]
Can anybody see where I've went wrong?
$counter = $counter++ will do nothing.
$counter++ increments the value of $counter, but evaluates to its current value (the one it had before incrementing). That way, you're setting $counter to have the value of itself, and that doesn't usually do much.
Simply do $counter++ instead.
(Additional info: there's also the pre-increment operator, ++$counter, which increments the variable and returns it new value.)
$counter = $counter++ will set $counter to its current value and then increment it by one. It is a redundant statement. If you do intend to just increment the variable $counter by 1 then just use $counter++.
I'm working with some data which is being retrieved from my database. It's placed into a 2-dimensional* array and manually sets the index based upon the ID of the data in the database.
* It's more than two-dimensional, but I only need to work with 2 dimensions of it.
This is the Array in question:
Array
(
[error] => Boolean(false)
[results] => Array
(
[1] => Array
(
[0] => title1
[4] => title2
)
[3] => Array
(
[0] => title3
[1] => title4
[2] => title5
)
[4] => Array
(
[0] => title6
[1] => title7
[3] => title8
)
)
)
Within this Array, I only need to work with the "results" part of it, hence making the problem Array 2-dimensional.
Some voodoo-magic happens in my script and I'm told the index for the first array and the index for the second array, and then I pull the value from the second array.
Let's say that I wanted to get the value "title5". My script would tell me that I need to use index 3 and then index 2.
I've done all of that, but it's this next part of the task that I'm stuck on, and have no-idea how to even attempt.
After retrieving "title5" I want to retrieve the indexes for the next and previous item, so in this case for both "title4" and "title6". In the event of there not being a previous value (say we originally pulled "title1") then I need some way of identifying this, like with a false boolean. And likewise for if there is no "next" value either.
By retrieve the indexes I mean, for example: title4 = 3 & 1 and title6 = 4 & 0
Does anybody have any ideas how I should go about doing this? I'm not looking for someone to do the work for me necessarily, but some pointers would be greatly appreciated. In the mean time I'll keep experimenting. Thanks!
Note:
Titles aren't actually called title1, title2, etc. So I can't just decrement a number and do a search.
I edited #Jonathan Rich's answer a little bit to obtain my actual solution. Where $firstIndex and $secondIndex are the two index that I already know.
//my already known indexes
$firstIndex = 3;
$secondIndex = 2;
//
$prevIndex1 = null;
$prevIndex2 = null;
$last_was_value = false;
$nextIndex1 = null;
$nextIndex2 = null;
foreach ( $articles['results'] as $index => $value ) {
foreach ( $articles['results'][$index] as $index2 => $value2 ) {
if ( ($index == $firstIndex) && ($index2 == $secondIndex) ) {
$last_was_value = true;
} else if ($last_was_value == true) {
$nextIndex1 = $index;
$nextIndex2 = $index2;
break 2;
} else if ($last_was_value == false) {
$prevIndex1 = $index;
$prevIndex2 = $index2;
}
}
}
echo "<br />PREV: $prevIndex1 & $prevIndex2<br />";
echo "NEXT: $nextIndex1 & $nextIndex2<br />";
Sure, this is a low level solution:
$prev = null;
$last_was_value = false;
$next = null;
foreach ( $foo['results'][$index1] as $index => $value ) {
if($value == $some_result_value) {
$last_was_value = true;
} elseif($last_was_value == true && $next == null) {
$next = $index;
} elseif($last_was_value == false) {
$prev = $index;
}
}
So in the end, if prev or next are null, then your index is the first/last index respectively, and if not then those values are the sibling indexes.