How to return array in php ? Actually I want to return whole value of $x[] insted of last index of $x[]. Please help me...
<?php
function top() {
require './php/connection.php';
$sql = "SELECT * FROM tbl_add";
$query = mysqli_query($connect, $sql);
$n = 0;
while ($result = mysqli_fetch_assoc($query)) {
$a[$n] = $result['add_id'];
$n = $n + 1;
}
$n = $n - 1;
for ($j = 0; $j < $n; $j++) {
for ($i = 0; $i < $n - 1 - $j; $i++) {
if ($a[$i] > $a[$i + 1]) {
$tmp = $a[$i];
$a[$i] = $a[$i + 1];
$a[$i + 1] = $tmp;
}
}
}
for ($i = 0; $i <= $n; $i++) {
echo $a[$i] . '<br>';
}
$j = 1;
for ($i = 0; $i <= 5; $i++) {
$r = $a[$i];
$sql = "SELECT * FROM tbl_add WHERE add_id='$r'";
$query = mysqli_query($connect, $sql);
$result = mysqli_fetch_assoc($query);
if ($result) {
$x[] = $result['mail'];
return $x[];
}
}
}
?>
return $x[]; is invalid syntax.
In expression $x[] = $result['mail'];, $x[] doesn't mean "the last element of $x". It is just a courtesy of PHP that spares the programmer of writing $x[count($x)]1 instead.
Returning an array is as easy as return $x; (given $x is an array).
Btw, there is no place in your code where $x is initialized as array. You just add values to some variable that doesn't exist, using the array syntax. PHP helps you and creates an array first and stores it in the $x variable but this practice is strongly discouraged. You should add $x = array(); somewhere before you use $x for the first time (outside the loop, of course). For example, you can put it before the line for ($i = 0; $i <= 5; $i++) {.
`
1 This statement is not entirely correct. However, if the values are added to the array using only the $x[] = ... syntax (as it happens in the posted code) then it is correct.
You have to return $x
Then when you call this function $data = top();
Now you get return data of function top to variable name data
// the code below will return $x as it is, independent of what it is. Array, integer, string etc..
Return $x;
// if you need to return two values use:
Return array($x, $y);
// again bit variables are returned as they are.
To call the function and get the values/array use:
$array = top();
Var_dump($array); //should be $x from your function
Related
Why this piece of code works when it is clearly wrong in the second for loop (for ($i==0; $i<$parts; $i++) {)?
Does php allows for multiple comparisons inside for loops?
function split_integer ($num,$parts) {
$value = 0;
$i = 0;
$result = [];
$modulus = $num%$parts;
if ($modulus == 0) {
for($i = 0; $i < $parts; $i++)
{
$value = $num/$parts;
$result[] = $value;
}
} else {
$valueMod = $parts - ($num % $parts);
$value = $num/$parts;
for ($i==0; $i<$parts; $i++) {
if ($i >= $valueMod) {
$result[] = floor($value+1);
} else {
$result[] = floor($value);
}
}
}
return $result;
}
Code for ($i==0; $i < $parts; $i++) runs because $i==0 has no impact on loop.
In normal for loop first statement just sets $i or any other counter's initial value. As you already set $i to 0 earlier, your loop runs from $i = 0 until second statement $i < $parts is not true.
Going further, you can even omit first statement:
$i = 0;
for (; $i < 3; $i++) {
echo $i;
}
And loop will still run 3 times from 0 to 2.
I am working on mathematical problem where the formula is: A[i] * (-2) power of i
where i=0,1,2,3,...
A is an array having values 0 or 1
Input array: [0,1,1,0,0,1,0,1,1,1,0,1,0,1,1]
Output is: 5730
Code
$totalA = 0;
foreach ($A as $i => $a) {
$totalA += $a * pow(-2, $i);
}
This is correct. Now I am looking for its opposite like:
Input is: 5730
Output will be: [0,1,1,0,0,1,0,1,1,1,0,1,0,1,1]
I am not asking for the exact code but looking for some logic from where I should start. I tried to use log() method but that did not return the desired output.
You were not looking for exact code, but I found this problem too interesting. This works:
function sign($n) {
return ($n > 0) - ($n < 0);
}
$target = -2396;
$i = 0;
$currentSum = 0;
// Look for max $i
while (true) {
$val = pow(-2, $i);
$candidate = $currentSum + $val;
if (abs($target) <= abs($candidate)) {
// Found max $i
break;
}
if (abs($target - $candidate) < abs($target - $currentSum)) {
// We are getting closer
$currentSum = $candidate;
}
$i++;
}
$result = [];
for ($j = $i; 0 <= $j; $j--) {
$val = pow(-2, $j);
$border = $val / 4;
if (sign($val) == sign($target) && abs($border) < abs($target)) {
array_unshift($result, 1);
$target -= $val;
} else {
array_unshift($result, 0);
}
}
echo json_encode($result);
First I look for the $i that gets me on or slightly above the $target. When found, I walk down and decide for each bit if it should be in the result.
As far as I can tell, these two programs should do exactly the same thing. However, the Python version works and the PHP one doesn't. What am I missing please?
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
my_list = [2,3,5,4,1]
bubbleSort(my_list)
print(my_list)
<?php
// Bubble Sort
$my_list = [2,3,5,4,1];
function bubble_sort($arr){
$size = count($arr);
for($pass_num = $size - 1; $pass_num >= 0; $pass_num--){
for($i = 0; $i < $pass_num; $i++){
if($arr[i] > $arr[$i + 1]){
swap($arr, $arr[i], $arr[$i+1]);
}
}
}
}
function swap(&$arr, $a, $b) {
$tmp = $arr[$a];
$arr[$a] = $arr[$b];
$arr[$b] = $tmp;
}
bubble_sort($my_list);
print_r ($my_list);
The sort is in fact working, but as you dont pass a reference to the bubble_sort($arr) function you never get to see the actual result. Telling bubble_sort() that the array is being passed by reference means you are changing $my_list and not a copy of $my_list
Oh and you had some compile errors, using $arr[i] instead of $arr[$i]
// Bubble Sort
$my_list = [2,3,5,4,1];
function bubble_sort(&$arr){ // <-- changed to &$arr
$size = count($arr);
for($pass_num = $size - 1; $pass_num >= 0; $pass_num--){
for($i = 0; $i < $pass_num; $i++){
if($arr[$i] > $arr[$i + 1]){
// also changed this line to pass just the indexes
swap($arr, $i, $i+1);
}
}
}
}
function swap(&$arr, $a, $b) {
$tmp = $arr[$a];
$arr[$a] = $arr[$b];
$arr[$b] = $tmp;
}
bubble_sort($my_list);
print_r ($my_list);
If you are testing this on a live server where error reporting is turned off add these lines to the top of any script you are developing, while you are developing it.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
And the compile errors would have shown on the web page
Bubble Sort Php
$data_set = [3,44,38,5,15,26,27,2,46,4];
function bubble_sort($data_set){
$number_of_items = count($data_set);
for($i = 0; $i <= $number_of_items - 2; $i++){
for($j = 0; $j <= $number_of_items -($i+2); $j++){
if($data_set[$j] > $data_set[$j + 1]){
$temp = $data_set[$j];
$data_set[$j] = $data_set[$j + 1];
$data_set[$j + 1] = $temp;
}
}
}
return $data_set;
}
echo '<pre>';
print_r(bubble_sort($data_set));
echo '</pre>';
I have the following code:
$extraPhoto_1 = get_field('extra_photo_1');
$extraPhoto_2 = get_field('extra_photo_2');
$extraPhoto_3 = get_field('extra_photo_3');
$extraPhoto_4 = get_field('extra_photo_4');
But I would like to rewrite it with a for loop, but I can't figure out how to put a variable within the value field. What I have so far is:
for($i = 1; $i < 5; $i++) {
${'extraPhoto_' . $i} = get_field('extra_photo_ . $i');
}
I've tried with an array like this:
$myfiles = array();
for ($i = 1; $i < 5; $i++) {
$myfiles["$extraPhoto_$i"] = get_field('extra_photo_ . $i');
}
Nothing seems to fix my problem. I'v searched on the PHP website (variable variable).
There is some bug in your code which not allowing. Use 'extra_photo_'. $i instead of 'extra_photo_. $i'
for($i = 1; $i < 5; $i++) {
$extraPhoto_.$i = get_field('extra_photo_'. $i);
}
You can build an array as defined below and than just call extract($myfiles) to access them as variables.
Again your syntax for the get field is incorrect you should append $i after the quotes.
$myfiles = array();
for ($i = 1; $i < 5; $i++) {
$myfiles["extraPhoto_".$i] = get_field('extra_photo_'.$i);
}
extract($myfiles);
If you want to create dynamic variable, use below code
for ($i = 1; $i < 5; $i++) {
${'extraPhoto_'.$i} = $_POST['extra_photo_'.$i];
}
if you want to assign variables to array use below code.
for ($i = 1; $i < 5; $i++) {
$myfiles["extraPhoto_$i"] = $_POST['extra_photo_'.$i];
/// $myfiles["extraPhoto_$i"] = get_field('extra_photo_'.$i);
}
and than to see if values are assign to new array or not, you can use below code.
echo "<pre>";print_r($myfiles);echo "</pre>";
I have written the following code to count the number of string occurrences in a given file.
PHP
<?php
$p = fopen("g.txt", "r");
$q = fread($p, filesize("g.txt"));
$t = explode(" ", $q);
$m = explode(" ", $q);
$i = 0;
$j = 0;
$r = 0;
$count = 0;
$c = count($t);
$d = array();
echo "count of".
"<br/>";
for ($i = 0; $i < $c; $i++) {
for ($j = $i; $j < $c; $j++) {
if ($t[$i] == $t[$j]) {
$count = $count + 1;
}
}
for ($r = $i + 1; $r < $c; $r++) {
if ($t[$i] == $t[$r])
unset($t[$r]);
}
echo $t[$i].
"=".$count.
"<br/>";
$count = 0;
}
?>
I am getting a notice of undefined offset on line numbers 17 and 24, though my output is coming out to be correct. Can you please help me in rectifying the above problem?
The problem is that you are deleting items from the array $t. You saved the count in $c, but the actual count will change by your last inner loop.
Even if you replace $c by count($t) everywhere, it will go wrong, because the last loop should be in reverse order, otherwise you skip items. For instance if you have the list 'a', 'b', 'c'. then when you delete 'b' and increment $r, you will not check 'c' at all.
So, if I fix those things, your code becomes as below. Although I didn't really check it for other issues. Frankly, I don't really get what is should do. ;-)
<?php
$p=fopen("g.txt","r");
$q=fread($p,filesize("g.txt"));
$t=explode(" ",$q);
$m=explode(" ",$q);
$i=0;
$j=0;
$r=0;
$count=0;
$d=array();
echo "count of"."<br/>";
for($i=0; $i<count($t); $i++)
{
for($j=$i; $j<count($t); $j++)
{
if($t[$i]==$t[$j])
{
$count=$count+1;
}
}
for($r=count($t) - 1; $r > $i; $r--)
{
if($t[$i]==$t[$r])
unset($t[$r]);
}
echo $t[$i]."=".$count."<br/>";
$count=0;
}
?>
In conclusion, you should do more tests. If the outcome of this script was okay, then it was by accident.