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];
}
Related
So I have an array:
$array = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
Obviously they're indexed 0-6.
I want to feed in a specific key index, and then reorder the array, beginning with that key, then going through the rest in the same order, like so:
print_r(somefunction(3, $array));
which would print this:
array
(
'0'=>'Wed',
'1'=>'Thu',
'2'=>'Fri',
'3'=>'Sat',
'4'=>'Sun',
'5'=>'Mon',
'6'=>'Tue'
)
Is there a core function that would do this, or does anyone have a quick solution?
UPDATE
Here's my final function, slightly bigger in scope than my question above, which utilizes AbraCadaver's answer:
public static function ordered_weekdays($format = 'abr')
{
$array = $format == 'full' ? array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday') : array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
return array_merge(array_splice($array, get_option('start_of_week'), count($array)-1), $array);
}
Because it's a nice one-liner, I didn't need to make it a separate function.
I've done this before and thought it was simpler than this, but here is what my brain says at the moment:
$index = 3;
$array = array_merge(array_splice($array, $index, count($array)-1), $array);
Try something along these lines...
function reorder($x,$y)
{
$c = count($y);
for ($i=0; $i<$c; $i++)
{
$newArray[$i] = $y[$x];
$x++;
if ($x > $c) $x = 0;
}
return($newArray);
}
function somefunction($n, array $a) {
$x = array_slice($a, 0, $n);
$y = array_slice($a, $n);
return array_merge($y, $x);
}
// forget this: uneccessary looping...
function somefunction($n, array $a) {
for($i = 0; $i < $n; $i++) {
array_push($a, array_shift($a));
}
return $a;
}
I need to add * in an array. This is how i do it in javaScript.
function makeStarString(grade) {
var starArray = [];
var starString = "";
for (var i = 0; i < grade; i++){
starArray[i] = "*";
starString = starString.concat(starArray[i]);
}
return starString;
}
The javascript version works fine but I cant make it work with php.
This is as far as i got with php.
function makeStarString($varGrade) {
$starArray = array ();
$starString = "";
for ($i = 0; $i < strlen($varGrade); $i++){
$starArray($i) = $star;
$starString = $starString.(starArray(i));
}
return $starString;
}
I get this error "Fatal error: Can't use function return value in write context" because of line $starArray($i) = $star;
The argument I send to the function is an Integer.
So the purpose of the function is that if i send a 5 to the function it will return *****
How can i fix my php function?
Use $starArray[$i] instead of $starArray($i) and starArray(i).
If you really need stars in an array, you don't need to use a loop:
$starArray = array_fill(0, $varGrade, '*');
and if you need to turn the array into a string:
$starString = implode('', $starArray);
But if you don't really ever need to use the array of stars, it would be easier to just use str_repeat:
str_repeat('*', $varGrade);
It would generally be a great idea to use strlen($varGrade) in a variable, because the foreach loop will have to count the length every iteration. This might bring performance issues.
Your $star variable is not defined, so I have no idea what you're trying to put there. Revise your own code.
Finally, you may use the .= operator to add something to existing string.
function makeStarString($varGrade) {
$starArray = array ();
$starString = "";
$length = strlen($varGrade);
for ($i = 0; $i < $length; $i++){
$starArray[$i] = $star;
$starString .= $starArray[$i];
// equivalent to $starString = $starString . $starArray[$];
}
return $starString;
}
UPDATE
If you send an int to the function, you don't need strlen:
function makeStarString($varGrade) {
$starArray = array ();
$starString = "";
for ($i = 0; $i < $varGrade; $i++){
$starArray[$i] = $star;
$starString .= $starArray[$i];
// equivalent to $starString = $starString . $starArray[$];
}
return $starString;
}
This code should work
function makeStarString($varGrade) {
$star = "*"; // star variable wasn't defined to.
$starArray = array ();
$starString = "";
for ($i = 0; $i < $varGrade; $i++){
$starArray[$i] = $star; // [ ] instead of ( )
$starString .= ($starArray[$i]); // $a.=$b instead of $a=$a+$b, added the $ at the i and [ ] instead of ( )
}
return $starString;
}
Is this what you need?
function makeStarString($varGrade) {
$starString = '';
for ($i = 0; $i < $varGrade; $i++) {
$starString .= '*';
}
return $starString;
}
A few notes on my modifications.
I don't see why you need that $starArray array in the first place. So I skipped it.
I revised your indentation. Strange indentation can make very simple code seem much more complicated than it really is. :)
You should ask if $i < $varGrade, not if $i < strlen($varGrade). If you ask by strlen(), then you get the width of the number you enter. For example, strlen(55) is 2, strlen(555) is 3, strlen(5555) is 4 etc. - ignoring the fact that it's a number. You just want the for-loop to give you $varGrade many stars so there is no need for strlen().
As a detail, I've put used single-quotes instead of double-quotes for strings because they're lighter (PHP doesn't parse variables inside them).
I hope it helps.
I have the following code, and I can't figure out what's wrong with it. I am supplying an array as an argument, and is_array($primes) returns true. Anything I'm missing here?
function generate_primes($max)
{
$i = 4;
$primes = [2, 3];
while($i < $max)
{
$isPrime = true;
foreach($primes as $value)
{
if($i % $value == 0)
{
$isPrime = false;
break;
}
}
if($isPrime)
$primes = $i;
$i++;
}
return $primes;
}
$primes = $i; shows that you re-assign the $primes variable after you find your first prime, 5. It no longer is an array at this point.
Instead, use this:
if($isPrime)
array_push($primes,$i);
Use php array type:
$primes = array(2, 3);
then later, when adding a new prime to the array:
array_push($primes, $i);
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.
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;
}
}