This will be a quick one for most of you I'm sure, but I'm banging my head against the wall trying to teach myself multidimensional arrays.
I simply wish to check whether or not $_FILES["Photo"]["name"] contains empty strings, and such the code below my if statement is executed.
Currently this works, as does my else statment (not shown), however there has to be a cleaner way of writing this??
Many thanks.
if (empty($_FILES["Photo"]["name"][0]) && empty($_FILES["Photo"]["name"][1]) && empty($_FILES["Photo"]["name"][2])) {
$query = "INSERT INTO lot (lotnumber, lottitle, lotdescription, datecreated, lastmodified) VALUES" .
"('$lotnumber', '$lottitle', '$lotdescription', NULL, NULL)";
if (!$mysqli->query($query)) {
echo '<p class="warning">Error executing INSERT query: (' . $mysqli->errno . ') ' . $mysqli->error . "</p>";
}
else
{
echo '<p class="success">The lot has been added to the directory.' . "</p>" . HTML_LINEBREAK;
}
}
You could use an array_filter(), but I don't really see the problem with what you are doing:
$test_array = array_filter($_FILES['Photo']['name'], function($var) {
return empty($var);
});
if (count($test_array) === 3) {
$query = ... // the rest of your code
}
Of course this assumes that there are only three elements in the array. If you only want to check the first 3 elements, you would want to add an array_slice() like this:
$test_array = array_filter(array_slice($_FILES['Photo']['name'], 0, 3), function($var) {
return empty($var);
});
I would have a script that counts the keys within the "name" level.
$count = sizeof($name_of_array->Photo->name);
Then in a for loop check to see if the keys are empty.
for($i = 0; $i <= $count; $i++)
{
if(empty($name_of_array->Photo->name[$i])
{
... continue code
}
else
{
... continue code
}
}
Related
i'm new in php. i just want to generate random names (or what you want...). it does works! but when i put in the middle of the code one "do/while" to control and avoid duplicates names it DOES NOT WORKS.... why? what's wrog with my code? i'm exhauste, destroyed.
<?php
require_once 'config.php';
require_once 'dbconn.php';
function getnome() {
$nome = ['tin', 'pin', 'nid', 'din', 'vin'];
return $nome[mt_rand(0, count($nome) - 1)];
}
for ($f =0; $f<6; $f++) {
$arr = [];
do {
$x = getnome();
}
while (in_array($x, $arr));
$arr[]=$x;
$query = "INSERT INTO ants (ant_id, nome) VALUES (NULL, '".getnome()."')";
$res = $mysqli->query($query);
if (!$res) {
echo('<br>Error' . $mysqli->error);
} else {
echo $mysqli->affected_rows . ' created';
}
}
?>
enter image description here
A simpler way to get unique values out of an array is to randomize the array and then process it in order.
$stmt = $mysqli->prepare("INSERT INTO ants (nome) VALUES (?)");
$stmt->bind_param("s", $a_nome);
$nome = ['tin', 'pin', 'nid', 'din', 'vin'];
shuffle($nome);
foreach ($nome as $a_nome) {
$stmt->execute();
}
There are two main problems:
You're reinitializing $arr with each iteration of the for loop, so it isn't actually keeping track of the random values you've already inserted. You need to initialize it before the for loop.
You're not using the non-duplicate value of $x you just got in the do... while loop in your insert statement. You're calling the getnome function again, which will give you another (possibly duplicate) value. You need to use $x instead.
$arr = []; // initialize $arr here instead
for ($f = 0; $f < 6; $f++) {
do {
$x = getnome();
}
while (in_array($x, $arr));
$arr[] = $x;
// use $x instead of getnome()
$query = "INSERT INTO ants (ant_id, nome) VALUES (NULL, '" . $x . "')";
$res = $mysqli->query($query);
if (!$res) {
echo('<br>Error' . $mysqli->error);
} else {
echo $mysqli->affected_rows . ' created';
}
}
Another problem you'll encounter once you've fixed the other two things is that you're trying to insert six unique values, but your getnome function can produce only five, so it looks like the do...while loop will become infinite on the last attempt. (That may just be something that got lost in translation when you created your example, but it is a possibility with while or do...while loops that you need to be careful about.)
Now a very kind StackOverflow use has helped me out with a lot of my issues however there's two remaining probelms with my code before it's ready to go, any ideas would be great as i'm currently screaming at it:
First of all i'm using the following to try and pull data from a MySQL Database, return it as a Numeric Array and Order It By ID. There's 2 items in there and no matter what I do I can only get 1 to display (I need it to display ALL data when the table fills up more):
$query = "SELECT * FROM batch ORDER by ID";
$result = $mysqli->query($query);
/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf ("%s (%s)\n", $row[0], $row[1]);
?>
Secondly, slightly off topic but this code below was given by a StackOverflow user however I can't get it to work, they've geared it to OOP which is not an area i'm familiar with and no matter what I do to correct the $this-> or public / private it still refuses to work (the aim of the code is to have a number in $userinput which gets checked against the $widgetBatches array for the closest match (i.e. input is 1100 and closest is 1000) this then gets deducted from the input (to leave 100) and the process loops again to check and this time returns 100 as the closest, this process continues until the $userinput reaches 0 or a negative number:
<?php
$userinput = 10000; // Our magic variable - user input
$iterations = 0;
function Widget($userinput)
{
$this->iterations++;
$widgetRequested = $userinput;
$widgetBatches = array("250", "500", "1000", "2000");
echo "Iteration " . $iterations;
echo "<br/>";
echo "Widget requested: " . $widgetRequested;
echo "<br/>";
$closest = GetClosest($widgetBatches, $widgetRequested);
echo "Closest: " . $closest;
echo "<br/>";
$widgetRemaining = $widgetRequested - $closest;
echo "Remainder: " . $widgetRemaining;
echo "<hr/>";
if($widgetRemaining > 0)
{
Widget($widgetRemaining);
}
else
{
echo "The value is now below or equaling zero: " . $widgetRemaining . "!";
}
}
function GetClosest($array, $value)
{
$lowest = null;
foreach($array as $val)
{
if($lowest == null || abs($value - $lowest) > abs($val - $value))
{
$lowest = $val;
}
}
return $lowest;
}
?>
This:
<?php
function Widget($input) {
$currentValue = $input; // Set internal variable from input (Think of this as an initial "remainder")
$i = 0;
$widgetBatches = [250, 500, 1000, 2000]; // Setup batch array
while ($currentValue > 0) { // While the remainder is more than 0
$i++;
echo "Iteration " . $i . "<br/>";
echo "Widget requested: " . $currentValue . "<br/>";
$closest = GetClosest($widgetBatches, $currentValue); // Find the closest value from batch array
echo "Closest: " . $closest . "<br/>";
$currentValue = $currentValue - $closest; // Work out new remainder
echo "Remainder: " . $currentValue . "<hr/>";
}
// Loop will exit when remainder is less than 0
echo "The value is now below or equaling zero: " . $currentValue . "!";
}
function GetClosest($array, $value) {
$result = null; // Innitialise the returned variable in case of failure
foreach($array as $val) { // For every array value, unless stopped
$result = $val; // Set result to current array value
if($value <= $result) break; // Stop foreach loop if value is less than or equal to result
}
return $result; // Return last result from Foreach loop
}
Widget(9000);
?>
Hopefully the comments are useful... I put more detail in than I would usually...
Did you try fetchAll(), I use PDO so not sure, but would suggest you use a while loop, like:
while ($result = $mysqli->query($query));
Or:
foreach($result as $r) then $r['data'];
I'm %100 sure the loop will iterate and pull out every data, which you can send to a table or a list.
I wrote query in php file ,my query is:
$query = "SELECT cc.NAME complex_check_name,f.name server_name,
sgk.NAME single_check_name,cc.operator
FROM complex_check cc,
lnksinglechecktocomplexcheck lk,
single_checks sgk,
functionalci f ,
lnkconfigurationitemtosinglecheck lkcg
WHERE cc.id = lk.complex_check_id AND
sgk.id = lk.single_check_id and
sgk.id = lkcg.single_check_id AND
lkcg.config_item_id = f.id ";
if ($result=mysqli_query($link,$query))
{
while ($obj=mysqli_fetch_object($result))
{
$list= $obj->complex_check_name .
"#".
$obj->server_name .
";".
$obj->single_check_name .
$obj-> operator;
echo $list .'<br>';
}
}
The result is :
test_com_check_sep01#INFRASEP01;cpu check sep01&
test_com_check_sep01#INFRASEP01;DB check sep01&
test_com_check_sep01#INFRASEP01;disk space check sep01&
test_com_check_sep02#INFRASEP02;cpu check sep02||
test_com_check_sep02#INFRASEP02;db check sep02||
test_com_check_sep02#INFRASEP02;disk space check sep02||
How can I concatenate the string as:
"test_com_check_sep01=INFRASEP01;cpu check sep01&INFRASEP01;DBcheck sep01&INFRASEP01;disk space check sep01"
"test_com_check_sep02=INFRASEP02;cpu check sep02||INFRASEP02;db check sep02||INFRASEP02;disk space check sep02"
You could store the values into an array and implode afterwards.
$check = array();
if($result = mysqli_query($link,$query)) {
while($obj = mysqli_fetch_object($result)) {
// If value is not stored in check array proceed
if(!in_array($obj->complex_check_name,$check))
$list[$obj->complex_check_name][] = $obj->complex_check_name."=";
$list[$obj->complex_check_name][] = $obj->server_name.";".$obj->single_check_name.$obj->operator;
// Store in check array
$check[] = $obj->complex_check_name;
}
// Loop through stored rows and implode with break
foreach($list as $array) {
echo implode("<br />",$array);
}
}
try this
$concat1 = '';
$concat2 = '';
if ($result=mysqli_query($link,$query))
{
while ($obj=mysqli_fetch_object($result))
{
if($obj->server_name == 'INFRASEP01'){
concat1 .= $obj->complex_check_name . "#".$obj->server_name .";". $obj->single_check_name . $obj-> operator;
}else{
concat2 .= $obj->complex_check_name . "#".$obj->server_name .";". $obj->single_check_name . $obj-> operator;
}
}
}
echo $concat1 .'<br>'.$concat2;
Assuming you want to keep the lines separate for use, you could do this
$list = array("INFRASEP01", "INFRASEP01", "INFRASEP02");
$concatINFRASEP01 = "";
$concatINFRASEP02 = "";
for($lineCounter = 0; $lineCounter < sizeof($list); $lineCounter++)
if(strpos($list[$lineCounter], "INFRASEP01") !== false){
//Found it
$concatINFRASEP01 .= " " . $list[$lineCounter];
}
else if(strpos($list[$lineCounter], "INFRASEP02") !== false){
$concatINFRASEP02 .= " " . $list[$lineCounter];
}
NOTE: I did not test this code so there may be errors.
If you do not need the $list array, then you can do as #Malakiof suggested.
EDIT (01/22/2015): I have improved my answer but left the old one there in case I misunderstood.
//In your case the rows come from the $obj (which most would call $row)
$listOfRows = array("test_com_check_sep01#INFRASEP01;cpu check sep01&","test_com_check_sep01#INFRASEP01;DB check sep01&", "test_com_check_sep02#INFRASEP02;cpu check sep02||");
//Create this array as you go through each row by adding the server_name
//to this array. You can skip making this array and simply make the
//unique array by checking if the array contains the server_name.
$listServerNames = array("INFRASEP01","INFRASEP02","INFRASEP01", "INFRASEP02", "INFRASEP01");
//Only have unique server names to avoid duplicates
$listUniqueServerNames = array_unique($listServerNames);
//this will be your list of concatenated strings
$concatByServerName = array();
//Go through the unique server names one by one
foreach($listUniqueServerNames as $serverName)
//While looking at each unique server name, look through the rows
foreach($listOfRows as $line)
if(strpos($line, $serverName) !== false){
//Found it
if(array_key_exists($serverName, $concatByServerName))
$concatByServerName[$serverName] .= " " . $line;
else
$concatByServerName[$serverName] = $line;
}
If the $listOfRows is very large, consider making a copy of $listOfRows and removing the lines from $listOfRows when you add them to $concatByServerName.
Although this is not the best way to do it, I am trying to keep it simple in order for you to be able to get it to work, while fully understanding what is happening. You can easily improve on this code by looking at your project and streamlining these tasks.
I am trying to use a FOREACH loop in PHP to output different messages depending on the position of the value in the array. My code is below:
$qtyValidFiles = count($validFiles);
$tick = 0;
foreach($validFiles AS $validItem)
{
if($tick = 0)
{
echo"'#$validItem,";
}
elseif($tick < $qtyValidFiles -1 && $tick != 0)
{
echo"#$validItem,";
}
elseif($tick = $qtyValidFiles -1)
{
echo"#$validItem'";
}
}; $tick++;
In this instance, $qtyValidFiles has 4 values.
The code above returns:
#Games'#Movies'#Music'#TV'
which suggests to me that $tick is always being seen as value 3.
If $validFiles is an indexed array, you can do:
foreach ($validFiles as $tick => $validItem)
instead of incrementing $tick yourself.
Your entire loop is unnecessary, though. You can do:
echo "'" . implode(",", array_map(function($x) { return "#$x"; }, $validFiles)) . "'";
This should be better than your code because you don't do the right thing if the array has exactly 1 item; you'll print the beginning quote and a comma, but I think you really want the one element surrounded by quotes.
$tick is always 0 because the $tick++; is outside of the loop. Move it up a line.
Also as Rahul Kumar states, use == as the comparison operator.
Or just do this, no loop needed:
echo '#' . implode(',#', $validFiles);
Seems like the simpler and correct equivalent to your code would be this:
$qtyValidFiles = count($validFiles);
$str = '';
foreach($validFiles AS $validItem) {
$str .= "#$validItem,";
}
if (!empty($str)) {
echo "'" . substr($str, 0, -1) . "'"; //removes the last ","
}
I have an array
$results = array(101, 102, 103, 104, 105)
I also have a input field where the user enters a number
<input type ="text" name="invoice" />
I put what the number that user enters in, into a variable
$id = $_POST['invoice']
How would I write an if statement to check to see if the number that user entered is in that array
I have tried doing in a for each loop
foreach($result as $value){
if($value == $id){
echo 'this';
}else{
continue;
}
is there a better way of doing this?
if (in_array($id, $results)) {
// ...
}
http://php.net/manual/en/function.in-array.php
Use in_array():
if (in_array($_POST['invoice'], $your_array)) {
... it's present
}
ok you can try this:
if ( in_array($id, $results))
{
// execute success
}
else
{
// execute fail
}
You can use in_array, like the others have suggested
if(in_array($id,$results)) {
//do something
} else {
$no_invoice = true;
}
but if you happen to want to use your array key for anything, you can kill two birds with one stone.
if($key = array_search($id,$results,true)) {
echo 'You chose ' . $results[$key] . '<br />';
}
Obviously for echoing you don't need my method - you could just echo $id - but it's useful for other stuff. Like maybe if you had a multi-dimensional array and element [0]'s elements matched up with element[1]'s elements.
If you are looking to compare values of one array with values of another array in sequence then my code is really simple: check this out it will work like this:
if (1st value of array-1 is equal to 1st value of array-2) { $res=$res+5}
if($_POST){
$res=0;
$r=$_POST['Radio1']; //array-1
$anr=$_POST['answer']; //array-2
$arr=count($r);
for($ac=0; $ac<$arr; $ac++){
if($r[$ac]==$anr[$ac]){
$res=$res+5;
}
}
echo $res;
}
Not quite.
your way is good enough, it only needs to be corrected.
foreach($results as $value){
if($value == $id){
echo 'this';
break;
}
}
is what you really wanted