For loop problem takes the third data as undefined - php

Controller
for ($x = 1; $x <= $numb; $x++)
{
echo $quanoutput = $this->input->post('quanoutput');
$barcodeoutput = $this->input->post('barcodeoutput');
$productsoutput = $this->input->post('productsoutput');
$outward_date=$this->input->post('outward_date');
$stock=$this->input->post('stock');
$warehouse_id =$this->input->post('warehouse_id');
$request_id =$this->input->post('request_id');
$warehouse=$this->input->post('warehouse');
$buyprice = $this->input->post('buyprice');
if ($productsoutput=='undefined'){
//$flag3 = $this->cartmodel->cartInsert($barcodeoutput,$quanoutput,$buyprice,$stock,$warehouse,$warehouse_id,$request_id,$outward_date);
} else {
$flag3 = $this->cartmodel->cartInsert($barcodeoutput,$quanoutput,$buyprice,$stock,$warehouse,$warehouse_id,$request_id,$outward_date);
}
}

Try starting your for loops at 0. (ie. j=0) and change the <= to just <.

Related

Decimals For negative PHP values

I am writing a bit of php code to output a random value
$max_mal = (3 - $oray);
$oray = 1;
$max = 100;
$total = 0;
for ($i = 0; $i < $max_mal; $i++){
$goli = mt_rand(3, 8);
$total += $goli;
$golis[] = $goli;
}
and for each loop goes here
foreach($golis as &$goli) {
$goli = floor(($goli / $total) * $max);
if ($goli == 0) {
$goli = 1;
}
}
$result = array_pad($golis, 3, -1);
shuffle($result);
$myresult = $result[0];
I am looking to get decimal values upto 5 numbers, but once a negative value comes it results out as 0.000-1 instead of -0.00001
$myresultb = str_pad($mario, 5, '0', STR_PAD_LEFT);
$myresultf = '0.'.$myresultb.'<br/>';
$total_score = 300;
echo $myresultf;
Secondly I am new to php learning so am I doing this PHP correct or it needs improvement
I have a div to show total score like this
<div id="total_score"></div>
and another div to show current score which value comes as echo $myresultf;
<div id="current_score"></div>
I want to update total score in real time with jquery wheneven button is clicked and <?php echo $myresultf ?> is refreshed in real time also
$("#play").click(function() {
var currentscore = $("#current_score").val();
var totalscore = $("#total_score").val();
how to do this.....
});
Try this:
$max = 100;
$oray = 1;
$max_mal = (3 - $oray);
$total = 0;
for ($i = 0; $i < $max_mal; $i++){
$goli = mt_rand(3, 8);
$total += $goli;
$golis[] = $goli;
}
foreach($golis as &$goli) {
$goli = floor(($goli / $total) * $max);
if ($goli == 0) {
$goli = 1;
}
}
$result = array_pad($golis, 3, -1);
shuffle($result);
$myresult = $result[0];
$negative_var=false;
if($myresult < 0)
{
$negative_var=true;
$myresult = 0-$myresult;
}
$myresultb = str_pad($myresult, 5, '0', STR_PAD_LEFT);
$myresultf = '0.'.$myresultb.'<br/>';
if($negative_var)
$myresultf="-".$myresultf;
$total_score = 300;
echo $myresultf;
simple use as follow:
$myresultb =str_replace('-','',$myresultb);
if($myresult == -1) {
$myresultf = '-0.'.$myresultb.'<br/>';
}
else {
$myresultf = '0.' . $myresultb . '<br/>';
}

PHP Error Undefined Offset

Getting Notice: Undefined offset: 25 in
C:\wamp\www\finalProjectDemo\search.php on line 32
I'm trying to read in from a file and search for a specific name and address within that for output. I know a database would be best. This is for a class assignment I'm giving out that's specifically set to work this way. I believe I almost have it all, but am just getting this problem. Fairly new to PHP.
I have this code:
<html>
<body>
<?php
// read lines into array
// search array for string
// get 7 lines from there.
$i = 0;
$fileName = "addresses.txt";
$readFile = fopen($fileName, 'r');
$readByLineArray = array();
// Get search string from submission
$searchFirstName = $_POST['searchFirstName'];
$searchLastName = $_POST['searchLastName'];
$searchFirstNameSuccess = 0;
$searchLastNameSuccess = 0;
while (!feof($readFile))
{
$readByLineArray[$i] = fgets($readFile);
//echo "$readByLineArray[$i] read from array position $i";
//echo "<br />";
$i++;
}
fclose($readFile);
$arrLength = count($readByLineArray);
$currentArrayPosition = 0;
for ($x=0;$x<=$arrLength;$x++){
if ($searchFirstName == $readByLineArray[$x])
{
$searchFirstNameSuccess = 1;
$x++;
if ($searchLastName == $readByLineArray[$x])
{
$searchLastNameSuccess = 1;
$currentArrayPosition = $x - 1;
} else {
$searchFirstNameSuccess = 0;
}
}
}
for ($y=0;$y<=7;$y++){
echo "$readByLineArray[$currentArrayPosition]<br />";
$currentArrayPosition++;
}
?>
</body>
</html>
Thanks for all your help!
Ben---
Try foreach :-
foreach ($readByLineArray as $temp){
if ($searchFirstName == $temp)
{
$searchFirstNameSuccess = 1;
$x++;
if ($searchLastName == $temp)
{
$searchLastNameSuccess = 1;
} else {
$searchFirstNameSuccess = 0;
}
}
}
Change your for loop like this..
for ($x=0;$x<$arrLength;$x++){ //<--- Should be < and not <=
Say if your array count is 3 , so the array elements keys are arranged as 0,1,2. When you put <= in the looping as condition , your code will check for an non-existent key with an index of 3 which will thrown an Undefined Offset notice.
EDIT :
The easier way....
<html>
<body>
<?php
$fileName = "addresses.txt";
// Get search string from submission
$searchFirstName = $_POST['searchFirstName'];
$searchLastName = $_POST['searchLastName'];
$searchFirstNameSuccess = 0;
$searchLastNameSuccess = 0;
foreach(file($fileName) as $recno=>$records)
{
if(stripos($records,$searchFirstName)!==false && stripos($records,$searchLastName)!==false)
{
$searchFirstNameSuccess = 1;
$searchLastNameSuccess = 1;
echo "Match Found at Position : $recno";
break;
}
}
?>
</body>
</html>

Undefined Offset 99171 in PHP

I got this Undefined Offset error from PHP, and I can't seem to see why. Can you guys help me out?
I'm pretty new to PHP, so I don't really understand what Undefined offset really is.
<?php
$wordlist = file('/tmp/all'); // 42M wordlist
$user = "admin";
$realm = "Miele Logic";
$nonce = "07ec2416ef0000009223000015000000";
$nc = "00000001";
$cnonce = "gdBxXVNT0y6npOpQ";
$qop = "auth";
$i = 0;
while($wordlist[$i]) {
$password = trim($wordlist[$i]);
$HA1 = md5("$user:$realm:$password");
$HA2 = md5("GET:/");
$response = md5("$HA1:$nonce:$nc:$cnonce:$qop:$HA2");
if($i % 100000 == 0) {
echo "$i\n"; // output $i at each 100k
}
if($response == '97b5e79866512f028266f34946117a2c') {
echo $password . "n";
break;
}
$i++;
}
?>
Change your code to:
$i = 0;
$count = count($wordlist);
while($i < $count) {
//rest of the code goes here
}

Optimized Logic to find high score

Basically this is related to a squash application where we have 2 scores. One is from winner point of view and another from loser point of view.
eg.
Score1: 11-5,11-5,11-5 (Winner point of view)
Score2: 5-11, 5-11,5-11 (Loser point of view)
Now in my logic i want to find which is the winner score and which is the loser score.
I have written my logic in the below way and it does work. But i want to know if their is any other better/optimized way of writing this.
$high1 = 0;
$high2 = 0;
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
$score1Array = explode(",",$score1);
$size = sizeof($score1Array);
for($i = 0; $i < $size; $i++) {
$checkscore1 = explode("-",$score1Array[$i]);
if($checkscore1[0] < $checkscore1[1]) {
$high1++;
}else if($checkscore1[0] > $checkscore1[1]) {
$high2++;
}
}
if($high1 > $high2) {
$winningScore = $score2;
$losingScore = $score1;
}else{
$winningScore = $score1;
$losingScore = $score2;
}
echo $winningscore;
echo $losingscore;
What about something like this:
function is_winning($score) {
$split_scores = preg_split('/(-|,)/', $score);
$wins = $losses = 0;
for($i = 0; $i < count($split_scores) / 2; $i += 2) {
if($split_scores[$i] > $split_scores[$i + 1])
$wins++;
if($split_scores[$i] < $split_scores[$i + 1])
$losses++;
}
return $wins > $losses;
}
Assuming $score is formatted as in your question. You can then use it like this:
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
if(is_winning($score1)) {
$winning_score = $score1;
$losing_score = $score2;
} else {
$winning_score = $score2;
$losing_score = $score1;
}
echo $winning_score;
echo $losing_score;
The idea is to split the score into an array where the even numbered indexes have the left score and the odd numbered indexes the right score. We then count the number of wins and the number of losses. If there's more wins then losses then we return true since the score was a winning score. If there's not more wins then losses we simply return false.
This should work
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
$l = $r = 0;
$score1_sets_arr = explode(',', $score1);
foreach ($score1_sets_arr as $set_score) {
$set_score_arr = explode('-', $set_score);
if ($set_score_arr[0] > $set_score_arr[1]) {
$l++;
} else {
$r++;
}
}
if ($l > $r) {
$winning_score = $score1;
$losing_score = $score2;
} else {
$winning_score = $score2;
$losing_score = $score1;
}
you can use this :
<?php
$high1 = 0;
$high2 = 0;
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
$explode = explode(",",$score1);
for($i=0;$i< sizeof($explode);$i++){
$explode2= explode("-", $explode[$i]);
if($explode2[0] <= $explode2[1]){
echo $explode2[0]."-";
echo $explode2[1]." ";
}
}
echo "<br />";
for($i=0;$i< sizeof($explode);$i++){
$explode2= explode("-", $explode[$i]);
if($explode2[1] >= $explode2[0]){
echo $explode2[1]."-";
echo $explode2[0]." ";
}
}
?>
for Winner point of view, all big score in left,otherwise in right. so u can just detect the first score.
$score1Array = explode(",",$score1);
$checkscore1 = explode("-",$score1Array[$i]);
if($checkscore1[0] < $checkscore1[1]) {
echo $score2;
echo $score1;
}else{
echo $score1;
echo $score2;
}
Fix: above code is wrong,try this:
$score1value = eval(str_replace(",","+",$score1));
$score2value = eval(str_replace(",","+",$score2));
if($score1value < $score2value) {
echo $score2;
echo $score1;
}else{
echo $score1;
echo $score2;
}

variable increment doesn't work

When I launch my web page, increment doesn't work correctly!
It should go like this: $i = from 1 to x (0,1,2,3,4,5,6 etc..).
But instead it jumps over every step giving result of (1,3,5,7 etc..).
Why is this code doing this?
<ul class="about">
<?php
$result = mysql_query("SELECT * FROM info WHERE id = 1");
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
$endBioTxt = explode("\n", $bioText);
for ($i=0; $i < count($endBioTxt);)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
$i++;
}
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
?>
</ul>
Output:
Sometext!(right side)
0
1
Sometext2!(right side)
2
3
...
Please DONT do this as other suggested:
for ($i=0; $i < count($endBioTxt); $i++)
do this:
$count = count($endBioTxt);
for ($i=0; $i < $count; $i++) {
}
No need to calculate the count every iteration.
Nacereddine was correct though about the fact that you don't need to do:
$i++;
inside your loop since the preferred (correct?) syntax is doing it in your loop call.
EDIT
You code just looks 'strange' to me.
Why are you doing:
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
???
That would just set $bioText with the last record (bio value) in the recordset.
EDIT 2
Also I don't think you really need a function to calculate the modulo of a number.
EDIT 3
If I understand your answer correctly you want 0 to be in the left li and 1 in the right li 2 in the left again and so on.
This should do it:
$endBioTxt = explode("\n", $bioText);
$i = 0;
foreach ($endBioTxt as $txt)
{
$class = 'left';
if ($i%2 == 1) {
$class = 'right';
}
echo '<li class="'.$class.'"><div>'.$txt.'</div></li>';
echo $i; // no idea why you want to do this since it would be invalid html
$i++;
}
Your for statement should be:
for ($i=0; $i < count($endBioTxt); $i++)
see http://us.php.net/manual/en/control-structures.for.php
$i++; You don't need this line inside a for loop, it's withing the for loop declaration that you should put it.
for ($i=0; $i < count($endBioTxt);$i++)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
//$i++; You don't need this line inside a for loop otherwise $i will be incremented twice
}
Edit: Unrelated but this isn't how you check whether a number is prime or not
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
This code works, please test it in your environment and then uncomment/comment what you need.
<?php
// This is how query should look like, not big fan of PHP but as far as I remember...
/*
$result = mysql_query("SELECT * FROM info WHERE id = 1");
$row = mysql_fetch_assoc($result);
$bioText = $row['bio'];
$endBioTxt = explode("\n", $bioText);
*/
$endBioTxt[0] = "one";
$endBioTxt[1] = "two";
$endBioTxt[2] = "three";
$endBioTxt[3] = "four";
$endBioTxt[4] = "five";
$totalElements = count($endBioTxt);
for ($i = 0; $i < $totalElements; $i++)
{
if ($i % 2)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
}
/*
// This is how you should test if all your array elements are set
if (isset($endBioTxt[$i]) == false)
{
echo "Array has some values that are not set...";
}
*/
}
Edit 1
Try using $endBioTxt = preg_split('/$\R?^/m', $bioTxt); instead of explode.

Categories