Problem with a while loop - php

My query does no return anything for my second index. It always sends me a message Notice: Undefined offset: 1. I tried doing with a for it is the same result, so I have read that my problem it is in the query, somebody told me let $stmt be null for freeing resources of my statement. I dont know what is wrong.
These are my methods. I dont know what to someone say use $database->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);
Example: $arrayDirectory[] = {'user1', 'user2'};
It must echo 1 2 but just prints me 1
for($i=0;$i<sizeof($arrayDirectory;$i++){
$res[$i] = $obj->obtainID($arrayDirectory[$i]);
echo $res[$i];
}
This is my obtainID method:
public function obtainID($user){
$conexion = $this->objConexion->configuracion();
$query = "CALL sp_xxx('$user')";
$stmt = $conexion->prepare($query);
$stmt->execute();
$resultado = $stmt->fetchColumn();
return $resultado;
}
$stmi = null where?

For one,
$arrayDirectory[] = {'user1', 'user2'};
is a syntax error. { ... } does not work for arrays in PHP. Maybe it's just a typo and you're getting PHP confused with javascsript.
But the bigger issue is the []. That tells PHP to treat $arrayDirectory as an array (fine), but PUSH as a single value whatever you're assigning.
If your code was really:
$arrayDirectory[] = array('user1', 'user2');
This would create the following structure:
array(1) {
[0]=>
array(2) {
[0]=>
string(5) "user1"
[1]=>
string(5) "user2"
}
}
Note that it's a 2-level array. A top level single-element array at index [0]. That element at 0 contains ANOTHER array, which contains your two usernames.
You should have this instead:
$arrayDirectory = array('user1', 'user2');
$res = array();
foreach($arrayDirectory as $user) {
$res[] = $obj->obtainID($user);
}

first of all you are wrong with your function, you forgot to add the ending ')' for sizeof function,also arrays aren't defined with { } you should use array( ) instead.
and finally you are doing a bad practice over there;
you should not call a function in a loop (sizeof()), like this every time the loop goes through it will initiate sizeof() function and it will take some resource, since sizeof($object) won't change while using the loop, you should save it in a variable
$sizeofobject = sizeof($object);
and use that variable in your loop instead

Related

What is the correct syntax for detecting an empty 2D array in PHP?

What is the correct syntax to detect an empty 2 Dimensional array in PHP? I have attempted to do so myself using the functions "isset()" and "!empty()" for both "2dArray[0]" and "2dArray[0][0]", but even with an empty array the result comes back positive. Here is a snippet of code from one of the times where I tried this:
if(isset($strengths[0][0]) || isset($sizes[0][0]))
{
print_r($strengths[0][0]);
echo "<br>blah<br>";
print_r($sizes[0][0]);
}
Yet the arrays are both empty. Using print_r we can even see that the arrays return nothing. Here is a picture example of a different attempt using isset(2dArray[0]):
In the picture you can see the array is also empty again.
It's important to note that I can use 2dArray[1] perfectly; it detects that there there is no second row as expected, but that means I cannot have any instances where there is only 1 row in either 2D array because it is positioned at position 0 with nothing at position 1 to be detected anyway.
What am I doing wrong?
Edit 1:
The code:
var_dump($strengths[0][0]);
var_dump($sizes[0][0]);
returns:
array(0) { }
array(0) { }
and the code:
var_dump($strengths[0]);
var_dump($sizes[0]);
returns:
array(1) { [0]=> array(0) { } }
array(1) { [0]=> array(0) { } }
Edit 2:
This is my init:
$sizes[][] = array();
This is where data is set:
foreach($products as $product)
{
//product information
foreach($mods as $mod)
{
//mod information
//when array is empty $mods is empty
if ($modType == "SIZE")
{
$sizes[$si][0] = $modValue . $modValueSuffix;
$sizes[$si][1] = $modPrice;
$sizes[$si][2] = $modID;
$si++;
$strengthOrSize = true;
}
}
}
I believe I should have done $sizes[] = array(); for a 2D array. I overlooked this because it's such a short piece of code I did not give it much attention.
You can do this to detect if the sub array is empty:
$arr = [[]];
if (!count($arr[0])) {
// do stuff
}

Why isn't my multidimensional array correctly initialized and/or returned?

I'm having the following problem:
I have this function where I pass a query result($matches_lines) as argument. In my function I get all the data I need from the query result and I'm trying to store it in a multidimensional array. My code is as follows:
function check_matches($matches_lines, $minage, $maxage, $actual_persontype){
$result = array(array());
$count = 0;
foreach($matches_lines as $lines){
$match_user = $lines["signup_username"];
$match_birth = $lines["signup_birth"];
$match_city = $lines["signup_city"];
$match_gender = $lines["signup_gender"];
$match_os = $lines["signup_os"];
$match_persontype = $lines["signup_persontype"];
if("some condition I want to verify"){
$new_add = array($match_user, $match_birth, $match_city, $match_gender, $match_os, $match_persontype);
array_push($result[$count], $new_add);
$count = $count+1;
}
}
return $result;
}
I call my function simply doing:
$matches_found = check_matches($matches_lines, $minage, $maxage, $actual_persontype);
I don't get errors by doing this, but when I try echoing one line
echo $matches_found[0][0];
I get a "HP Notice: Undefined offset: 0".
What am I doing wrong?
Edit: var_dump($matches_found) returns "array(0) { }"
while var_dump($matches_lines) returns
object(PDOStatement)#3 (1) { ["queryString"]=> string(277) "SELECT s.signup_username, s.signup_birth, s.signup_city, s.signup_gender, s.signup_os, s.signup_persontype
FROM signups s
WHERE s.signup_username <> 'leonardo' && s.signup_city = 'Torino' && s.signup_os = 'Windows'" }
The problem of your code definitely lies in your condition. It matches no line and therefore the result contains no values for the inner array.
If there are no matches, you result will look like this:
$matches_found = [
0 => [/*This array does not contain an index 0, because it is empty*/]
];
Therefore the call $matches_found[0][0] throws an error for the second 0, because the inner array is empty.
Since you did not provide the condition we can not help you with fixing it.
The reason I can tell that this is the error is, that your code behind the condition contains an error and you said I don't get errors. Therefore it is never executed.
The line array_push($result[$count], $new_add) expects the first parameter $result[$count] to be an array. This is true for the first iteration, because you initialize $result with [[]]. For the second call with $count = 1 there will be no field in $result with the index 1. You will therefore either get an "Undefined offset: 1" error or "function array_push expects parameter 1 to be of type array. null given" error.
This can be fixed by using the native PHP handling for appending values to an array:
$result[] = [$new_add];
$result[] = will handle the appending of a new element and [$new_add] is an array that contains one element, the new row. If you do not need it to be wrapped in an extra array ($new_add is an array itself already) you can omit the brackets around it.
Note, that in order to let this work correctly you have to initialize $result with $result = []; instead of $result = [[]]; ( or array() instead of array(array())).
PHP will then take care of the new indices itself. You can remove the $count variable.

Merge arrays with strings and delete repetitive values in PHP

From WP_Query I am dumping strings stored into separate arrays:
array(1) {
[0]=>
string(8) "Portugal"
}
array(1) {
[0]=>
string(5) "Spain"
}
array(1) {
[0]=>
string(5) "Italy"
}
array(1) {
[0]=>
string(6) "Monaco"
}
array(1) {
[0]=>
string(5) "Spain"
}
array(1) {
[0]=>
string(9) "Lithuania"
}
I am trying to merge those arrays into one array, delete repetitive strings like "Spain" and get the number of unique values.
I was trying to use array_merge():
$tester = array();
foreach($array_string as $value) {
array_merge($tester, $value);
}
$result = array_unique($tester);
print_r($result);
But without any decent results, error telling that <b>Warning</b>: array_merge(): Argument #2 is not an array Could someone tell where I am missing the point? Many thanks for all possible help, will be looking forward.
The code posted in the question is almost good. The intention is correct but you missed out a simple thing: you initialize $tester with an empty array and then never add something to it. In the end, it is still empty and array_unique() has nothing to do but return an empty array too.
The error is in the line:
array_merge($tester, $value);
array_merge() does not change the arrays passed to it as argument. It returns a new array that your code ignores (instead of saving it into $tester).
This is how your code should look like:
$tester = array();
foreach($array_string as $value) {
$tester = array_merge($tester, $value);
}
$result = array_unique($tester);
print_r($result);
Solution #2
You can use call_user_func_array() to invoke array_merge() and pass the values of $array_string as arguments. The returned array contains duplicates; passing it to array_unique() removes them:
$result = array_unique(call_user_func_array('array_merge', $array_string));
Solution #3
A simpler (and possibly faster) way to accomplish the same thing is to use array_column() to get the values into an array and then pass it to array_unique(), of course:
$result = array_unique(array_column($array_string, 0));
This solution works only with PHP 5.5 or newer (the array_column() function doesn't exist in older versions.)
To get the number of unique strings in the merged array you will have to set empty array before WP_Query
$tester = array();
Than inside while loop of WP_Query every string is put into separate array and pushed to $tester
foreach((array)$array_string as $key=>$value[0]) {
array_push($tester,$value);
}
Unique values in array $tester is found using array_unique() functions that should be placed after WP_Query while loop.
$unique_array_string = array_unique($tester, SORT_REGULAR);
$unique_string_number = sizeof($unique_array_string);
You will create an array and will take key of the array for cities names like spain..etc And it will give different cities name always...
$data= array();
$data1 = array("Portugal");
$data2 = array("Spain");
$data3 = array("Italy");
$data4 = array("Monaco");
$data5 = array("Spain");
$data6 = array("Lithuania");
$merge = array_merge($data1, $data2,$data3,$data4,$data5,$data6);
$data = array();
foreach($merge as $value) {
$data[$value] = $value;
}
echo '<pre>',print_r($data),'</pre>';

Trouble with extracting a value from an associative array

I am having some basics trouble with PHP. I want to retrieve an average of a column of numbers from a MYSQL database. I am using SELECT AVG() to get the result in the database. The issue is that what is returned is not a floating number but an associative array with one key:value. This is the kind of thing I am getting back in json form:
array(1) { [0]=> array(1) { ["AVG(enterpriseAppDev.employee.age)"]=> string(7) "54.4538" } }
In my PHP project I am assigning the above to a variable $average.
Can anyone tell me how I can extract the value (54.4538) the the $average variable and use it later on?
I have tried to use a foreach loop to get the value like this
foreach ($average as $x => $x_value) {
$average = $x_value;
return $average;
}
I have also tried to do the standard Deviation in SQL using STDEV and STDEVP but I get an error saying these functions do not exist.
Any help would be much appreciated.
2 problems :
you assign the value $average into the loop whereas it is in the loop parameter... can cause a crash...
so you could use return $x_value without getting it into $average.
then, you don't need a loop here just do this (with NO loop)
return $average[0]['AVG(enterpriseAppDev.employee.age)']
if you really want a loop you can do this :
foreach ($average as $line_number => $line) {
foreach($line as $key => $x_value) {
return $x_value;
}
}
1.
If you'll always get this multidimensional array you can reset the internal pointer of the array with reset to "flatten" the first one. And this should do the trick:
var_dump(reset($average[0]));
// or you can do it twice to get the same result as before
$average = reset($average);
var_dump(reset($average));
2.
But probably you can get a better key name using an alias in your SQL:
SELECT AVG() AS myavg
// so you should end up with a result like:
$queryResult = array(
array(
"myavg" => "54.4538"
)
);
// and get the average
$average = reset($queryResult);
var_dump($average['myavg']);
3.
Or even more weird, if you're using php 5.4 where you can get an array reference directly from a function result:
var_dump(reset($average)['avg']);

PHP: Assigning values to a variable inside IF statement

I was wondering if i could assign values to a variable inside an IF statement. My code is as follows:
<?php
if ((count($newArray) = array("hello", "world")) == 0) {
// do something
}
?>
So basically i want assign the array to the $newArray variable, then count newArray and check to see if it is an empty array.
I know i can do this on several lines but just wondered if i could do it on one line
Try this:
if(count($newArray = array("Hello", "world")) == 0) {
....
}
I'd advice against this though, as it makes your code less readable. And highly illogical too as you know that the array in question contains two values. But perhaps you have something else in mind. :)
Yeah, you can, like so:
if(count($ary = array(1,2,3)))
Doing a var_dump of $ary gives:
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
Actually you don't need to use count inside the if statement, because an empty array is considered to be false in PHP. See PHP documentation.
So your code can look like this:
if (!$newArray = array("hello", "world")) {
echo "newArray is empty";
}

Categories