Hello I have this code which selects from a list of 20 items 12 and from those 12 1 is randomly selected and echoed:
class Gamble
{
public static function doPointsCheck()
{
global $Gamble;
$Gamble_points = '2';
if($Gamble_points <= 1)
return false;
else
return true;
}
public static function Spin()
{
global $Wheel;
if(!self::doPointsCheck())
return 'You need way too more points to gamble';
else
{
$Result = array();
$Result = range(1, 12);
shuffle($Result);
$Result = array_slice($Result, 0, 20);
$SendToCheck = self::CheckPrize($Result);
}
}
public static function CheckPrize($Array)
{
global $Wheel;
echo '<h1>List of items you can win today:</h1><form action="class.MysticWheel.php" method="post">';
for($i = 1; $i <= count($Array); $i++)
{
$Won = '<p>'.$Wheel[$Array[$i]]['pseudo'].'</p>';
echo $Won;
}
echo '<input name="Feeling lucky" type="submit" value="Feeling Lucky" /></form>';
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
$i = rand( 1, 12 );
$Prize = '<p>'.$Wheel[$Array[$i]]['pseudo'].'</p>';
echo $Prize;
}
}
}
When I test it I recieve the following error:
Notice: Undefined offset: 12 on line 54
Notice: Undefined index: on line 54
So i won't show the last item, it will only show 11 possible items that could have been won and get the notice.
How can I fix it?
$Result = range(1, 12);
-->
foreach (range(1, 12) as $number) {
$Result[] = $number;
}
Try this.
Related
This question already has answers here:
"Fatal error: Cannot redeclare <function>"
(18 answers)
Closed 2 years ago.
I have a nested recursive function it's a task from codewars.
persistence(39) === 3; // because 3 * 9 = 27, 2 * 7 = 14, 1 * 4 = 4
and 4 has only one digit persistence(999) === 4; // because 9 * 9 * 9
= 729, 7 * 2 * 9 = 126, 1 * 2 * 6 = 12, and finally 1 * 2 = 2;
persistence(4) === 0; // because 4 is already a one-digit number
which throws :
Fatal error: Cannot redeclare rec();
function persistence(int $num): int {
$str = (string)$num;
$nums = str_split($str);
$count = count($nums);
if( $count === 0 ){
return 0;
}
$x = 0;
function rec($nums, $n) {
$result = [];
for ($i = 0; $i < count($nums); ++$i) {
if ($i == 0) {
$result = $nums[$i];
} else {
$result *= $nums[$i];
}
}
$num = implode('',$nums);
$diff = $num - $result;
if ( $diff != 0 ) {
$n += 1;
$result = str_split($result,1);
return rec($result, $n);
}
return $n;
}
$result = rec($nums,$x);
return (int)$result;
}
I've tried to use an variable function
$rec = 'rec';
$result = $rec($nums,$n)
but there are another error : `
Fatal error: Cannot redeclare rec()
`
PHP 7.4 version. Can anyone explain me what the problem is ?
Don't define the function inside the other function:
You have:
function persistence(int $num): int {
// code ...
function rec($nums, $n) {
// code ...
}
}
This means that the function rec should be created each time the function persistence gets called.
You should define them first:
function persistence(int $num): int {
// code ...
}
function rec($nums, $n) {
// code ...
}
And then call them to your liking, for example like you already do:
$rec = 'rec';
$result = $rec($nums,$n)
i have this function sort_by_time, the purpose of this function is to swap the time1 if the time2 is greater than time1 but my problem is im having an error of Undefined offset: 0. Sometimes the error is Undefined offset: 1. or Undefined offset: 2. Can someone help me to prevent this error in my code? I'm thinking this in these last 3 days but i can't think of any solution on this.
in this line the error occur.
if (Payroll2::convert_time_in_minutes($_time[$j]->time_in) > Payroll2::convert_time_in_minutes($_time[$j+1]->time_in))
This error occurs because the $_time[0] is not set.
Sample time. This is dynamic not only limited to 3 sometimes it's 4, sometimes it's 5 or 1.
1 => {#6356}
2 => {#6352}
3 => {#6257}
Here's my full function code
public static function sort_by_time($_time)
{
$count = 0;
$n = count($_time);
for ($i = 0; $i < $n-1; $i++)
{
for ($j = 0; $j < $n-$i-1; $j++)
{
if (Payroll2::convert_time_in_minutes($_time[$j]->time_in) > Payroll2::convert_time_in_minutes($_time[$j+1]->time_in))
{
// swap temp and arr[i]
$temp = $_time[$j];
$_time[$j] = $_time[$j+1];
$_time[$j+1] = $temp;
}
}
}
return $_time;
}
Try this:
public static function sort_by_time($_time)
{
usort($_time,function($ad,$bd)
{
$ad = Payroll2::convert_time_in_minutes($ad->time_in);
$bd = Payroll2::convert_time_in_minutes($bd->time_in);
if ($ad == $bd) {
return 0;
}
return $ad < $bd ? -1 : 1;
});
return $_time;
}
if it doesn't work the problem can be in function Payroll2::convert_time_in_minutes
I have this code:
public function getYears()
{
for($yearNum = 1; $yearNum <= 12; $yearNum++){
$year[]=$this->year;
echo $year[$yearNum]=$yearNum;
}
return $yearNum;
}
I have this error:
PHP Warning – yii\base\ErrorException
Invalid argument supplied for foreach()
How can i return this 12 numbers?
As per your comments:
i need only 12 numbers(1,2,3,4,5,6,7,8,9,10,11,12) without 0
You can get 12 numbers by using this:
public function getYears()
{
for($yearNum = 1; $yearNum <= 12; $yearNum++){
//$year[] = $yearNum;
$year[] = $yearNum;
//echo $year[$yearNum]=$yearNum;
}
return $year;
}
// calling function
$result = $this->getYears();
//echo "<pre>";
$numbers = implode(",", $result);
echo $numbers; //1,2,3,4,5,6,7,8,9,10,11,12
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>
I'm creating a php calculator that needs to use the following classes, then print off the users name and the average score they achieved. This is the code I have so far, but it's not displaying correctly, it's saying there are missing arguments and undefined variables but i'm not sure where i've gone wrong!
<?php
class person {
public $name;
}
class student extends person {
function student ($name, $grade1, $grade2) {
if(is_numeric($grade1) && is_numeric($grade2)){
$grades = array($grade1, $grade2);
}
elseif (is_numeric($grade1)) {
$grade2 = 0;
}
else {
$grade1 = 0;
}
}
function average ($grades) {
$length = count($grades);
$total = 0;
for ($i = 0; $i < $length; $i++) {
$total = $total + $grades[i];
}
$average = $total / $length;
return $average;
}
}
$person1 = new student ($_POST['firstName'], $_POST['firstGrade1'], $_POST['firstGrade2']);
$person2 = new student ($_POST['secondName'], $_POST['secondGrade1'], $_POST['secondGrade2']);
$person3 = new student ($_POST['thirdName'], $_POST['thirdGrade1'], $_POST['thirdGrade2']);
echo "<br/> $person1->name" . "achieved an average of" . "$person1->average();";
echo "<br/> $person2->name" . "achieved an average of" . "$person2->average();";
echo "<br/> $person3->name" . "achieved an average of" . "$person3->average();";
?>
ERROR MESSAGES:
Warning: Missing argument 1 for student::average(), called in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\my portable files\Exercise 4\average.php on line 40 and defined in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\my portable files\Exercise 4\average.php on line 22
Notice: Undefined variable: grades in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\my portable files\Exercise 4\average.php on line 23
Warning: Division by zero in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\my portable files\Exercise 4\average.php on line 30
You don't appear to be returning that $grades variable. It's probably not defined because you aren't returning anything.
Your method:
function student ($name, $grade1, $grade2) {
if(is_numeric($grade1) && is_numeric($grade2)){
$grades = array($grade1, $grade2);
}
elseif (is_numeric($grade1)) {
$grade2 = 0;
$grades = array($grade1, $grade2);
}
else {
$grade1 = 0;
$grades = array($grade1, $grade2);
}
return $grades
}
Will need to look more like that. You'll also want to actually add grade1 and grad2 to your returned array in your alternate conditions.
The following is the classes enhanced. You will notice that they have constructors and functions to request variables. Private variables are usually the preferred method as they are protected and therefore cannot be modified outside the class.
class person {
private $name = "";
public function __construct ($nameV) {
$this->name = $nameV;
}
public function getName() {
return $this->name;
}
}
class student extends person {
private $grades;
public function __construct ($name, $grade1, $grade2) {
parent::__construct($name);
if ( ! is_numeric($grade1)) { $grade1 = 0; }
if ( ! is_numeric($grade2)) { $grade2 = 0; }
$this->grades = array($grade1, $grade2);
}
public function average () {
$length = count($this->grades);
$total = 0;
for ($i = 0; $i < $length; $i++) {
$total = $total + $this->grades[$i];
}
$average = $total / $length;
return $average;
}
}
The export code is then simply:
echo "<br/>" . $person1->getName() . " achieved an average of " . $person1->average();
echo "<br/>" . $person2->getName() . " achieved an average of " . $person2->average();
echo "<br/>" . $person3->getName() . " achieved an average of " . $person3->average();
Due to not having the form, I tested with the following data:
$person1 = new student ("XYZ", 1, 2);
$person2 = new student ("XYZ2", 100, 20);
$person3 = new student ("XYZ3", 95, 94);
Which exported:
XYZ achieved an average of 1.5
XYZ2 achieved an average of 60
XYZ3 achieved an average of 94.5