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
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'm running a simple script which puts an integer through the formula of the Collatz conjecture and adds the output of each step into an array.
I want to use a function to detect if there's a cycle in the array, using Floyd's algorithm. And though I feel like I'm not doing a bad job, I don't seem to get it right. At this moment I'm getting the error Trying to get property 'next' of non-object in C:\xampp\htdocs\educom\week3\functions.php on line 12
See my code below. Any feedback is greatly appreciated!
include("functions.php");
$n = $_POST['number'];
$step = 0;
$reeks1 = array();
$cycle = 0;
echo "Your entry is: ". $n ."<br><br>";
while($n!==1 && $cycle==0){
$cycle = detect_cycle(array($reeks1));
if($n % 2 == 0){
$n = $n / 2;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}else{
$n = ($n * 3) + 1;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}
}
functions.php:
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node->next;
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit->next == NULL){
return FALSE;
}else{
$turtle = $turtle->next;
$rabbit = $rabbit->next->next;
}
}
return FALSE;
}
Check this out. IMPORTANT I don't know is this according to your theory. but it won't give you errors if you use like this.
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node[0];
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit[0] == NULL){
return FALSE;
}else{
$turtle = $turtle[0]; // use the number of the element key starting from 0
$rabbit = $rabbit[0][1];
}
}
return FALSE;
}
class fruits
{
function g($str = 'fruits'){
$i=0;
$new_str = "";
while ($i < strlen($str)-1){
$new_str = $new_str + $str[$i+1];
$i = $i + 1;
}
return $new_str;
}
function f($str = 'fruits') {
if (strlen($str)== 0) {
return "";
}
else if (strlen($str)== 1)
{
return $str;
}
else
{
return $this->f($this->g($str)) + $str[0]; }
}
function h($n=1, $str = 'fruits'){
while ($n != 1){
if ($n % 2 == 0){
$n = $n/2;
}
else
{
$n = 3*$n + 1;
}
$str = $this->f($str);
}
return $str;
}
function pow($x, $y){
if (y==0)
{
return 1;
}
else
{
return $x * $this->pow($x, $y-1);
}
}
}
$obj = new fruits;
print(h(pow());
I only want to ask how to echo a function like this print(h(pow);?
First turn on error reporting with:
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
?>
And you will see (Besides the typos):
Fatal error: Call to undefined function h() in ...
That is because you have a class with methods. So you have to take an instance of your class an call the method from it, e.g.
$obj = new fruits;
echo $obj->h($obj->pow(4, 5));
This is basic OOP PHP. Also I would highly recommed you to use more meaningful function and variable names!
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.
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