Putting Incremental values in array - php

I have the following code
<?php
for ($i=1; $i<=4; $i++)
{
echo $i . "<br>";
}
?>
which Results 1 2 3 4
I have another code which have a variable $number = 1 and coding is as follows
if ($number = $i)
{
echo "Message" ;
}
MY issue is i need to check the variable $number(1) is available in the list of values displayed by variable $i.
Can anybody find a solution for that? Thanks in advance .

You should use == (comparison operator) instead of = to compare two values within an if statement, as follows:
if ($number == $i)
{
echo "Message" ;
}
However, assuming that it's just a typo, here is my suggestion:
You can store the numbers to be printed in an array first.
$i = array(1,2,3,4);
foreach($i as $num)
{
echo $num."<br/>" ;
}
Then, you can use the in_array() function of php to check if $number is present in any of the numbers printed above.
if(in_array($number, $i))
{
echo "Message" ;
}

try this this will put your incremental values in array and after that you can validate with any number
$inc=array();
for ($i=1; $i<=4; $i++)
{
array_push($inc,$i);
}
$number=1;
if(in_array($number, $inc))
{
echo "your Message" ;
}

= is the assigment operator, to compare you have to use ==
if ($number == 1) {
//...
}
Furthermore there are situatons where using
if ($number = $value) {
//...
}
is of use. this code would assign $value to $number and 'return' its value, therefore if ($number = 1) echo "hi"; will echo "hi" - while `if ($number = 0) echo "hi"; will output nothing. A assign like the above is quite useless, it is mostly used when you call a function, you want to restore its return value and compare it in the same step like
if ($number = getValue()) {
//$number is set to getValue() and is not 0, null or false
}

Related

I dont know what to do with this PHP Code

The code below basically helps in finding out if a number is a Palindromic Number or not. Although I get my execution done with the output, I just can seem to handle all the "screams" and fatal errors that I get. How do I handle this. Just a beginner and trust you can explain in a way that I may be able to understand..
<?php
for ($num = 1; $num <= 20; ++$num){
$_array1 = str_split($num);
//print_r($_array1);
//echo "<br/>";
$_array2 = array_reverse($_array1);
//print_r($_array2);
//echo "<br/>";
$i = 0;
$j = 0;
while ($i < sizeof($_array1) && $j < sizeof($_array2)){
if ($_array1[$i] == $_array2[$j]){
++$i;
++$j;
}
}
if ($_array1[$i] == $_array2[$j]){
echo "The number $num is a Palindrome Number";
}
}
?>
You get to the size of elements, which is 1. However, if your array has only one element, which is the case for 1-digit numbers, then sizeof($_array) === 1. Which means that the biggest possible index you can use is 0. You need to change your code to something like this:
<?php
for ($num = 1; $num <= 20; ++$num){
$_array1 = str_split($num);
//print_r($_array1);
//echo "<br/>";
$_array2 = array_reverse($_array1);
//print_r($_array2);
//echo "<br/>";
$i = 0;
$j = 0;
$different = false;
while ((!$different) && ($i < sizeof($_array1))){
if ($_array1[$i] == $_array2[$j]){
++$i;
++$j;
} else {
$different = true;
}
}
if (!$different){
echo "The number $num is a Palindrome Number";
}
}
?>
But you are inversing the array without a need to do so and you are looping for unnecessarily long. I propose this function to determine whether an array is a palindrome:
function isPalindrome($input) {
$size = count($input);
for ($index = 0; $index < $size / 2; $index++) {
if ($input[$index] != $input[$size - $index - 1]) {
return false;
}
}
return true;
}
Note, that:
the function assumes that the keys of the array are numbers
the function uses a single array
the size of the array is stored into a local variable to not calculate it repeatedly
the cycle cycles until half of the array, since going beyond that is unnecessary, due to the symmetrical nature of the != operator
the function returns false when the first difference is found, to further optimize the checking
if there were no differences, the function returns true, representing that the input is a palindrome

globally scoped variable not returning from function

I think I've been staring at this too long, but why won't $sum echo 23?
(I'm aiming to have a global scoped $sum injected in to a function and returned when the function is complete)
<?php
$sum = 0;
function find_divisible() {
for ($i = 0; $i < 10; $i++) {
if ($i % 5 == 0) {
echo "<br>".' $sum is equal to '.$sum.' and $i is equal to '.$i;
$sum += $i;
}elseif ($i % 3 == 0) {
echo "<br>".' $sum is equal to '.$sum.' and $i is equal to '.$i;
$sum += $i;
}else {
echo "<br/>$i is not divisible...";
}
}
return $sum;
}
find_divisible($sum);
echo "<br>";
echo $sum;
?>
So in your code you have 3 main errors/problems:
1. You forgot the following line in your function (at the top)
global $sum;
2. You return $sum, but you don't assign the function call to a variable, so you can remove it
3. You pass $sum as an argument to the function, but the function doesn't takes any arguments, so delete all parameters in the function call
But to archive your goal i see 3(4) different ways!
1. With global variables (Which you do now (But i wouldn't recommend that, because later you get really confused and encapsulation? you can forget that if you use global))
2. You can pass the variable as argument, your code would looks something like this:
$sum = 0;
function find_divisible($sum) {
//Code
return $sum;
}
$sum = find_divisible($sum);
echo $sum;
3. You can pass the variable by reference, your code would looks something like this:
$sum = 0;
function find_divisible(&$sum) {
//^ See here
//Code
}
find_divisible($sum);
echo $sum;
(4). You don't have to use any parameter if you say $sum is always 0 and you just return $sum and assign it to a variable, your code would looks something like this:
function find_divisible() {
$sum = 0;
//Code
return $sum;
}
$sum = find_divisible();
echo $sum;
(Hope this answer helps you, i think it's always good to see different ways/solutions)
You could pass the $sum as a reference like this:
function find_divisible(&$sum) {
// code here
}
But you wouldn't need to return it from the function. Any changes made to it in the function would be made to the original variable you passed into find_divisible($sum)
Just use the global keyword.
global $sum;
Although, I'd recommend taking it in as a parameter like so.
function find_divisible($sum) {
...
}

mysqli_fetch_array stop / multiple usage

I tried to use mysqli_fetch_array twice in a code, and it seems not to work.
<?php
$i=1;
while ($i < $x)
{
while($data=mysqli_fetch_array($result))
{
echo $i;
echo $data['ID'];
}
}
while {$i > $x)
{
while($data=mysqli_fetch_array($result))
{
echo $i;
echo $data['ID2']
}
}
?>
This doesn't work for the second case. Why? Is there any way to get my idea to work?
I want to use some of the array values in one place, and some in another
After you fetch all rows the pointer is at the end of the result set and you cannot fetch more. You need to reset it to the first row before attempting to fetch from it again:
mysqli_data_seek($result, 0);
Alternately, the first time through assign rows to an array and use that later:
while($data=mysqli_fetch_array($result)) {
$rows[] = $data;
}
foreach($rows as $row) {
//whatever
}
Depending on what you are doing not a great way to split up rows, but based on your comments (you have to increment your counter):
$i=1;
while($data=mysqli_fetch_array($result) && $i < 11) {
echo $data['ID'];
$i++;
}
while($data=mysqli_fetch_array($result) && $i < 21) {
echo $data['ID2'];
$i++;
}
Where are you resetting the vars, also you should do the while loop like this:
while ( ($i < $x) || ($data=mysqli_fetch_array($result) ) )

Display even & odd numbers

I am trying loop through an array of random numbers if the the number is dividable by two then it's even and I then want to assign this to an array $even[], and if odd then assign it to the odd array. I have managed to display the results without using an array but for the sake of this I want to put them into their own array. However I can't seem to get this result I'm after all I get is this error: message Array to string conversion.
<?php
$numbers = array();
for ($i=0; $i<=1000; $i++) {
$numbers[]=mt_rand(1,1000);
if ($i % 2 == 0){
$even[]=$i;
} else {
$odd[]=$i;
}
}
echo $even;
echo $odd;
?>
Try this to echo the results.
foreach ($even as $evens){
echo $evens . '<br/>';
}
define $odd and $even as a array
$even = array();
$odd = array();
check if($i%2 == 0)
{
$even[] = $i;
}
else
{
$odd = $i;
}
var_dump($even);
var_dump($odd);

PHP for loop not getting all posted values

I have a HTML Form where i can add rows dynamically, every time a row is added the number in my input field goes up each time
each row there are 4 input fields and each one has the number on the end of the name
on my submit page i have this PHP for loop:
for($x=1;$x<=$_POST["number"];$x++)
{
}
but its only getting one posted value
i have tried changing to:
for($x=0;$x<=$_POST["number"];$x++)
{
}
but this does the same thing
for ($x = 0; $x < count($_POST['number']); $x++)
{
echo "Number: $_POST['number'][$x]";
}
// OR:
foreach ($_POST['number'] as $number)
{
echo "Number: $number";
}
You have to add the count() function and use < instead of <= or else you will get an:
index out of range error.
Try this:
for ($x = 0; $size = count($_POST['number']); $x < size; $x++)
{
echo "Number: $_POST['number'][$x]";
}
Bad practice:
for ($x = 0; $x < count($_POST['number']); $x++)
{
echo "Number: $_POST['number'][$x]";
}
Why? The array size is fetched on every iteration and this will make your code run slower.

Categories