Undefined offset: 9, Undefined variable - php

Error at this line: $an = explode(";", $f[$i]);
This one too: if ($wasone) (Undefined variable)
Any help? Thank you.
<?
if ($_POST["submit"])
{
$a = answer();
$out = "Q: $ask<br>A: ".$a;
$tile = ($cfg["scrolling"]) ? $tile : "";
echo "$out<br>$tile";
echo "<input name='tile' type='hidden' id='tile' value='$out<br>$tile'>";
}
// answers
function answer()
{
global $cfg, $ask;
$ask = (empty($ask)) ? "<empty>" : $ask;
$kick = array("?","\n");
$ask = str_replace($kick,"",$ask);
$f = file($cfg["answersfile"]);
for ($i=0; $i<=count($f); $i++)
{
$an = explode(";", $f[$i]);
$a = $an[0];
if (strstr($a,trim($ask)))
{
if ($wasone)
{
return("Please be more concrete");
}
array_shift($an);
array_pop($an);
$ai = rand(0, count($an)-1);
// answering
$wasone = true;
$retval = $an[$ai];
}
}
$retval = (empty($retval)) ? "I dont understand you. Please try again." : $retval;
return $retval;
}
?>

the condition in the for loop should be
$count = count($f);
for ($i=0; $i<$count; $i++)
without the '=' to ensure that only indexes accessed range from 0 to count-1

The line
for ($i=0; $i<=count($f); $i++)
should probably be
for ($i=0; $i<count($f); $i++)
count() returns the number of elements of $f, which is one more than the index of the last element of $f (in this case nine). You want to stop before $i gets past the index of the last element

By default array indexes begin from 0. If count($f) === 9, then it means your array there has indexes 0, 1, 2 ... 8. If you loop while $i <= 9, then you will try to access element with index 9 ... which is not there.

Related

Create an array from pairwiseDifference function

this is my code:
$arry = (10,20,30,40,50)
function pairwiseDifference($arry, $n)
{
$diff = 0;
for ($i = 0; $i < $n - 1; $i++)
{
// absolute difference between
// consecutive numbers
$diff = abs($arry[$i] - $arry[$i + 1]);
echo $diff." ";
}
}
// Driver Code
$n = sizeof($arry);
echo "<br> Percent of commisions are: "; pairwiseDifference($arry,$n); // this echo 10,10,10,10
So now i wanna make the results of pairwise funcition an array to use in another code, i tried to put:
$arru = pairwiseDifference($arry,$n)[1];
$arru1 = pairwiseDifference($arry,$n)[2];
$arru2 = pairwiseDifference($arry,$n)[3];
$arru3 = pairwiseDifference($arry,$n)[4];
echo $arru;
echo $arru1;
echo $arru2;
echo $arru3;
But are not working.
What im wrong?
Thanks in advance!
An array declaration in PHP needs to either have the array keyword or it can just be declared with square brackets []:
$arry = array(10,20,30,40,50);
or
$arry = [10,20,30,40,50];
You can get the size of an array with the count() method, and there is no need to pass it as a parameter to your function:
function pairwiseDifference($arry)
{
$n = count($arry);
// ...
}
Your function doesn't return anything, so the variables $arru, $arru1, ... won't get anything back from the function and will remain empty. In order to return an array of differences and solve your problem you can do this:
function pairwiseDifference($arry)
{
$n = count($arry) - 1; // you can add the -1 here
$diff = 0;
$result = array();
for ($i = 0; $i < $n; $i++)
{
// absolute difference between
// consecutive numbers
$diff = abs($arry[$i] - $arry[$i + 1]);
echo $diff." ";
array_push($result, $diff); // use array_push() to add new items to an array
}
return $result; // return the result array
}
$arry = array(10,20,30,40,50);
echo "<br> Percent of commisions are: ";
// this echos 10,10,10,10 and assigns whatever your function returns
// to the variable $diffArray
$diffArray = pairwiseDifference($arry);
$arru = $diffArray[0]; // array elements start at index 0
$arru1 = $diffArray[1];
$arru2 = $diffArray[2];
$arru3 = $diffArray[3];
echo $arru; // prints 10
echo $arru1; // prints 10
echo $arru2; // prints 10
echo $arru3; // prints 10

get a set of values from an array

i have a set of arrays:
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
what i want to do is to get a set of $data array from each number of $nums array,
the output must be:
output:
2=11,22
3=33,44,55
1=66
what i tried so far is to slice the array and remove the sliced values from an array but i didn't get the correct output.
for ($i=0; $i < count($nums); $i++) {
$a = array_slice($data,0,$nums[$i]);
for ($x=0; $x < $nums[$i]; $x++) {
unset($data[0]);
}
}
Another alternative is to use another flavor array_splice, it basically takes the array based on the offset that you inputted. It already takes care of the unsetting part since it already removes the portion that you selected.
$out = array();
foreach ($nums as $n) {
$remove = array_splice($data, 0, $n);
$out[] = $remove;
echo $n . '=' . implode(',', $remove), "\n";
}
// since nums has 2, 3, 1, what it does is, each iteration, take 2, take 3, take 1
Sample Output
Also you could do an alternative and have no function usage at all. You'd need another loop though, just save / record the last index so that you know where to start the next num extraction:
$last = 0; // recorder
$cnt = count($data);
for ($i = 0; $i < count($nums); $i++) {
$n = $nums[$i];
echo $n . '=';
for ($h = 0; $h < $n; $h++) {
echo $data[$last] . ', ';
$last++;
}
echo "\n";
}
You can array_shift to remove the first element.
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
foreach( $nums as $num ){
$t = array();
for ( $x = $num; $x>0; $x-- ) $t[] = array_shift($data);
echo $num . " = " . implode(",",$t) . "<br />";
}
This will result to:
2 = 11,22
3 = 33,44,55
1 = 66
This is the easiest and the simplest way,
<?php
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
$startingPoint = 0;
echo "output:"."\n";
foreach($nums as $num){
$sliced_array = array_slice($data, $startingPoint, $num);
$startingPoint = $num;
echo $num."=".implode(",", $sliced_array)."\n";
}
?>

if ( isset inside a function for loops

I'm try to write a custom function trying to avoid to rewrite the if(isset everytime I call an array in a loop:
function ifvalueexists($valueexists){
if(isset ($valueexists ) ){
$newvalue = $valueexists;
return $newvalue;
}
else {
$newvalue = '';
}
return $newvalue;
}
TEST:
$myarray = array(1, 2, 3);
for ($i = 0; $i < 5; ++$i){
echo ifvalueexists($myarray[$i]);
}
but I still get: Undefined offset: 3 and Undefined offset: 4. What am I doing wrong? Thanks!
The data access is taking place before you're calling the function. You are trying to send a non-existent array index as a parameter to the function. You can get this to work, but you need to pass the entire array as a parameter along with the index you are attempting to access in order to avoid invalid indices, something like this:
function ifvalueexists(array $value, $index) {
if(isset ($value[$index] ) ){
return $value[$index]; // why not just return the value directly?
}
return ''; // no need for else here
}
If you wanted to do this in one line, you could do that too:
function ifvalueexists(array $value, $index) {
return isset($value[$index]) ? $value[$index] : '';
}
I think you may be overcomplicating your code. This is just a one liner, rather than the 10+ lines of code you have.
$myarray = array(1, 2, 3);
for ($i = 0; $i < 5; ++$i){
echo (isset($myarray[$i])) ? $myarray[$i] : '';
}
You can use array_key_exists:
$myarray = array(1, 2, 3);
for ($i = 0; $i < 5; ++$i){
if(array_key_exists($i , $myarray)
echo $myarray[$i];
}

php variable after a variable in for loop

I need a way to do this
for($i=1;$i<=10;$i++){
$id$i = "example" . $i;
}
notice the second line has $id$i
so for the first loop $id1 will equal example1
in the second loop $id2 will equal example2
and so on...
Thank you very much!
You can use variable variable names to do this; however, it's probably much more convenient if you just used an array:
for($i = 1, $i <= 10, $i++) {
$id[] = "example" . $i;
}
You can convert a string into a variable (the name of the variable), if you put another $ in front of it:
$str = "number";
$number = 5;
$$str = 8;
echo $number; // will output 8
So in your example, you could do it like that:
for($i = 1; $i <= 10; $i++) {
$str_var = "id".$i;
$$str_var = "example".$i;
}
It would be much better to use an array, but you could do this:
for($i=1; $i<=10; $i++){
$var ="id$i";
$$var = "example" . $i;
}
Here's what I would recommend doing instead:
$ids = array;
for($i = 1; $i <= 10; $i++) {
$ids[$i] = "example" . $i;
}
You could create an array of size $i with a name of $id, and insert each element into a different index.
for($i=1;$i<=10;$i++){
$id[$i] = "example" . $i;
}
$var = array();
for($i=1; $i<=10; $i++) {
$var['id' . $i] = 'example' . $i;
}
extract($var, EXTR_SKIP);
unset($var);
but why not use a simple array?

dynamically creating array in php

I am trying to create arrays dynamically and then populate them by constructing array Names using variable but I am getting the following warnings
Warning: in_array() expects parameter 2 to be array, null given
Warning: array_push() expects parameter 1 to be array, null given
For single array this method worked but for array of arrays this is not working. How should this be done?
<?php
for ($i = 1; $i <= 23; ++$i)
{
$word_list[$i] = array("1");
}
for ($i = 1; $i <= 23; ++$i)
{
$word = "abc";
$arrayName = "word_list[" . $i . "]";
if(!in_array($word, ${$arrayName}))
{
array_push($$arrayName , $word);
}
}
?>
Why are even trying to put array name in a variable and then de-reference that name? Why not just do this:
for ($i = 1; $i <= 23; ++$i)
{
$word = "abc";
$arrayName = "word_list[" . $i . "]";
if(!in_array($word, $word_list[$i]))
{
array_push($word_list[$i] , $word);
}
}
You get the first warning because your $arrayName variable is not actually an array, you made it into a string.
So instead of:
$arrayName = "word_list[" . $i . "]";
You should have this:
$arrayName = $word_list[$i];
You get your second warning because your first parameter is not an array.
So instead of:
array_push($$arrayName , $word);
You should have this:
array_push($arrayName , $word);
If you make these changes you will get an array that looks like this in the end:
$wordlist = array( array("1", "abc"), array("1", "abc"), ... ); // repeated 23 times
And in the for loop, you are accessing the array the wrong way
Here is your corrected code
for ($i = 1; $i <= 23; ++$i)
{
$word = "abc";
$arrayName = $word_list[$i];
if(!in_array($word, $arrayName))
{
array_push($arrayName , $word);
$word_list[$i] = $arrayName;
}
}

Categories