PHP - Weak Type Declaration For Integers
Is it possible to perform type declaration which allows either an integer or a string digit (i.e. ctype-digit) instead of the following? function someFunction(int $id){} Looking at functions.arguments.type-declaration, I expect not. If not, would you recommend type casting before calling the function or removing type declaration from the function and performing the check manually within the function and throwing an applicable exception? Thanks Similar Tutorialshow do I pull out two random integers at the same time without ever possibly choosing the same integer twice? Code: [Select] if( date('j') < 1 && > 14) { $EnrollDate = "1/".date('n')."/".date('y'); }else { $EnrollDate = "15/".date('n')."/".date('y'); } What could be wrong here, i cant work! hi there, i am fairly new to OOPs in php, i get an error when i declare the argument type (as object) in a function and pass the same type (object). class eBlast { public static function getEmail(object $result) { return $result->email; } } $r = mysql_fetch_object($query); eBlast::getEmail($r); echo gettype($r); // outputs: object error is : Code: [Select] Catchable fatal error: Argument 1 passed to eBlast::getEmail() must be an instance of object, instance of stdClass given, called in C:\wamp\www\integra\client\pl_eblast\admin\send_emails.php on line 145 and defined in C:\wamp\www\integra\client\pl_eblast\app\app.eBlast.php on line 8 if i remove the type declaration in the function it works, but just would like to know why it shows error when pass the same type, also isnt mysql_fetch_object is the instance of stdclass? thanks in advance! I almost have this right, but not quite. I am trying to echo out the average score if a person scored above 70 and my averaging isn't correct. It should echo out 89, but instead the number is 63.25. The averaging is the only part not working. Everything else works as intended. I might not have my curly braces in the proper order or something. I think it's something stupid I am forgetting. Here is my code. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Array Test</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body> <?php function array_average_nonzero($scores) { return array_sum($scores) / count(array_filter($scores)); } $scores["Tim"] = 98; $scores["Tom"] = 80; $scores["Mike"] = 50; $scores["Jason"] = 25; foreach( $scores as $key => $value) if($value < 70){ echo "$key scored a $value which is less than 70. <br />\n"; } elseif ($value < 70); { echo "The average score of those who scored over 70 is: " .array_sum($scores) / count($scores) . "<br />"; } ?> </body> </html> Hi everybody, a few dasy ago i found a function which translates integers into text like this:
echo $number->written_number(101); // one hundred one
but i've got a problem, this function works fine on russian language, but that this function translate in 3 languages:
russian, english and ukrainian like this:
echo $number->written_number(101); // сто один - one hundred one - сто один
how can i add english and ukrainian languages?
When i tried to add this manually, it was okay but in one moment i received error, and all my script is broked, and now i don't know what to do, i've got a few hours to complete this test work, but unfortunately i've got no idea how to do this(
Pls help me somebody, i will infinitely grateful!!!
This is my code
<?php require_once('languages.php'); class numberTransfer extends languages { public function written_number($i, $female = false) { if (($i < 0) || ($i >= 1e9) || !is_int($i)) { return false; // Аргумент должен быть неотрицательным целым числом, не превышающим 1 миллион } if($i == 0) { return $this->N0. '</br>' .$this->N0eng; } else { return preg_replace( array('/s+/','/\s$/'), array(' ',''), $this->num1e9($i, $female) ); return $this->num1e9($i, $female); } } public function num_125($n) { /* форма склонения слова, существительное с числительным склоняется одним из трех способов: 1 миллион, 2 миллиона, 5 миллионов */ $n100 = $n % 100; $n10 = $n % 10; if(($n100 > 10) && ($n100 < 20)) { return 5; } elseif($n10 == 1) { return 1; } elseif(($n10 >= 2) && ($n10 <= 4)) { return 2; } else { return 5; } } public function num1e9($i, $female) { if($i < 1e6) { return $this->num1e6($i, $female); } else { return $this->num1000(intval($i/1e6), false) . ' ' . $this->Ne6[$this->num_125(intval($i/1e6))] . ' ' . $this->num1e6($i % 1e6, $female); } } public function num1e6($i, $female) { if($i < 1000) { return $this->num1000($i, $female); } else { return $this->num1000(intval($i / 1000), true) . ' ' . $this->Ne3[$this->num_125(intval($i/1000))] . ' ' . $this->num1000($i % 1000, $female); } } public function num1000($i, $female) { if($i < 100) { return $this->num100($i, $female); } else { return $this->Ne2[intval($i/100)] . (($i % 100)?(' '. $this->num100($i % 100, $female)):''). '</br>' .$this->Ne2eng[intval($i/100)]. (($i % 100)?(''. $this->num100($i % 100, $female)):'') ; } } public function num100($i, $female) { $gender = $female?1:0; if ($i < 20) { return $this->Ne0[$gender][$i]. '</br>' .$this->Ne0eng[$gender][$i]; } else { return $this->Ne1[intval($i / 10)] . (($i % 10)?(' ' . $this->Ne0[$gender][$i % 10]):''). '</br>' . $this->Ne1eng[intval($i / 10)] . (($i % 10)?(' ' . $this->Ne0eng[$gender][$i % 10]):''); } } } $number = new numberTransfer(); echo $number->written_number(101);as you can see i tried to glue array with russian language words with array with english laguage words. Probably i've got somethink like this: $number = new numberTransfer(); echo $number->written_number(101); сто один one one hundredодин one damn bullshit... Please people help me:) I am wondering how can I insert integers in the database without manually input it in the form. I am looking to fill the product_id and customer_id table. I would do it but only by sequence and '' quotes at the VALUE part of an INSERT statement. Also condition the insert of product_id and customer_id according to the id in the SESSION variable. Code: [Select] <?php session_start(); if (isset($_SESSION['id'])) { $userid = $_SESSION['id']; $username = $_SESSION['username']; $fname = $_POST['firstname']; $lname = $_POST['lastname']; $telephone = $_POST['telephone']; $city = $_POST['city']; $state = $_POST['state']; $itemname = $_POST['product_name']; $price = $_POST['price']; $details = $_POST['details']; $category = $_POST['category']; $subcategory = $_POST['subcategory']; $product_id = $_POST['product_id']; $customer_id = $_POST['customer_id']; $date_sold = $_POST['date_sold']; $sqlinsert = "INSERT INTO customers (id,firstname,lastname,telephone,city,state,product_name,price,details) VALUES('','$fname','$lname', '$telephone','$city','$state','$itemname','$price','$details')"; $sqlinsert2 = "INSERT INTO products (id,product_name,price,details,category,subcategory) VALUES('','$itemname','$price','$details','$category','$subcategory')"; $sqlinsert3 = "INSERT INTO sales (id,product_id, customer_id, date_sold) VALUES('','$product_id','$customer_id','$date_sold')"; $enterquery = mysql_query($sqlinsert) or die(mysql_error()); $enterquery2 = mysql_query($sqlinsert2) or die(mysql_error()); $enterquery3 = mysql_query($sqlinsert3) or die(mysql_error()); } ?> The above insert its respective fields in each table but how is it possible to INSERT it according to the SESSION['id]; so that it INSERT according to the costumer id plus that it generates and INSERT automatically in the product_id and customer_id related to the product_id and customer_id fields in products and customer table? without manually doing it. any references will be appriciated because the above code seems like the product_id and customer_id won't INSERT in relations to the customer and product table. One more thing the product_id and customer_id won't be pass from the form to this file but rather a value will be INSERT it in their field according to the id in customer and products table. i hit a wtf moments print $_POST['idName']; // prints 0, correct, the value of the selected select element item is indeed 0 print '<br>'; $value = intval($_POST['idName']); // otherwise its a string if($value == 'empty') { print '<br>wtf does this get printed?'; } the $values value is the number zero, not the string 'empty', so why does it eval as one? Hi,
Is there any way to use the inbuilt filter functions in PHP to filter for integer values greater than 256? All examples that I saw had a max_range of 256. Kindly suggest. Thanks.
Hi, I'm trying to retrieve the integer value between the <span> tag from a HTML source code.
HTML source code:
<span> (3861822) </span>This is the php code: <!DOCTYPE html> <html> <body> <?php //use curl to get html content function getHTML($url,$timeout) { $ch = curl_init($url); // initialize curl with given url curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set useragent curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // write the response to a variable curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects if any curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds to execute curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error return @curl_exec($ch); } $html=getHTML("http://www.alibaba.com/Products",10); preg_match("/<span>(.*)<\/span>/i", $html, $match); $title = $match[1]; echo $title; ?> </body> </html>Whenever I try to run it, this error will come out: Notice: Undefined offset: 1 in C:\xampp\htdocs\myPHP\index.php on line 19. How to correct it so that it will display all the integer value within the tag name but without the bracket? Thanks Edited by Raex, 20 August 2014 - 01:38 AM. Well the topic may not sound very explicit. So I'll do my best to explain it here. I have a pull down menu as part of a form, which contains the months of the year. I'm trying to store the value of this form entry using the $_POST['month'] variable into a database but first, I need to convert the month values into their corresponding integer values( that is 1 for January, 2 for February etc), in order to easily do date calculations later down the road. Any ideas about how to do this? It may be helpful to include the code for the pull down menu. Code: [Select] <p><tab> Date of Birth: <?php //Make the month pull down menu. //Array to store months. $months = array (1 => 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); print '<select name= "month">'; foreach ($months as $key => $value) { print "\n<option value=\"$key\">$value</option>"; } print '</select>'; ?> </tab> <tab> <?php //Make the day pull down menu print '<select name= "day">'; for ($day = 1; $day <= 31; $day++) { print "\n<option value=\"$day\">$day</option>"; } print '</select>'; ?> </tab> <tab><?php //Make the year pull down menu print '<select name= "year">'; $start_year = date('Y'); for ($y = ($start_year - 18); $y >= 1900; $y--) { print "\n<option value=\"$y\">$y</option>"; } print '</select>'; ?> </tab> </p> I'm getting an error like : Fatal error: Declaration of Cog\YouTrack\Rest\Authenticator\CookieAuthenticator::authenticate (Cog\Contracts\YouTrack\Rest\Client\Client $client): Cog\YouTrack\Rest\Authenticator\void must be compatible with Cog\Contracts\YouTrack\Rest\Authenticator\Authenticator::authenticate (Cog\Contracts\YouTrack\Rest\Client\Client $client): Cog\Contracts\YouTrack\Rest\Authenticator\void in /var/www/html/vendor/cybercog/youtrack-rest-php/src/Authenticator/CookieAuthenticator.php on line 24 my index file is : require_once 'vendor/autoload.php'; use Cog\YouTrack\Rest; // use Cog\Contracts\YouTrack\Rest\Authenticator\Authenticator; // Application configuration (replace with your YouTrack server values) $apiBaseUri = 'http://111.111.111.111:8080'; $apiUsername = 'username'; $apiPassword = 'password'; // Instantiate PSR-7 HTTP Client $psrHttpClient = new \GuzzleHttp\Client([ 'base_uri' => $apiBaseUri, 'debug' => true, ]); // Instantiate YouTrack API HTTP Client $httpClient = new Rest\HttpClient\GuzzleHttpClient($psrHttpClient); // Instantiate YouTrack API Cookie Authenticator $authenticator = new Rest\Authenticator\CookieAuthenticator(); CookieAuthenticator.php file is : namespace Cog\YouTrack\Rest\Authenticator; use Cog\Contracts\YouTrack\Rest\Authenticator\Authenticator as AuthenticatorContract; use Cog\Contracts\YouTrack\Rest\Client\Client as ClientContract; /** * Class CookieAuthenticator. * * @package Cog\YouTrack\Rest\Authenticator */ class CookieAuthenticator implements AuthenticatorContract // <--line 24 where the error is { /** * @var string */ private $username = ''; /** * @var string */ private $password = ''; /** * @var string */ private $cookie = ''; /** * Determine is trying to authenticate. * * @var bool */ private $isAuthenticating = false; /** * CookieAuthenticator constructor. * * @param string $username * @param string $password */ public function __construct(string $username, string $password) { $this->username = $username; $this->password = $password; } /** * Authenticate client and returns cookie on success login. * * @param \Cog\Contracts\YouTrack\Rest\Client\Client $client * @return void * * @throws \Cog\Contracts\YouTrack\Rest\Authenticator\Exceptions\AuthenticationException */ public function authenticate(ClientContract $client): void { $client = new ClientContract; if ($this->cookie !== '' || $this->isAuthenticating) { return; } $this->isAuthenticating = true; $response = $client->request('POST', '/user/login', [ 'login' => $this->username, 'password' => $this->password, ]); $this->isAuthenticating = false; if ($response->isStatusCode(200)) { $this->cookie = $response->cookie(); } } /** * Retrieve authentication token. * * @return string */ public function token(): string { return $this->cookie; } } Why I'm getting this error? I think there is something wrong with CookieAuthanticator.php file but unfortunately I could not find it Edited May 24, 2019 by Rommeo I am wonrdering what the best type of http header to declare for a product page the is trying to display a product that is either not active at the moment or no longer available. Basically is google was trying to reach product-details.php?product-id=50 but that $_GET didn't return any results from the DB, I typically have a message that says "That product does not exist or is unavailable at this time.", but it's just a else{} that is showing that and not declaring any http error like 404.
I don't think 404 would be appropriate though cause I don't want it to be can't find type error I think since the product might just be inactive at the moment. Maybe I am wrong and it should be a 404 error, or is there a more appropriate error to use? I am mostly concerned about the http header for search engines since the message I display is more than enough for users on the page.
Probably a stupid question . . .
The MIME type in my php.ini file is set to text/html:
default_mimetype = "text/html"But, because I use XHTML 1.0 Strict, the MIME type of my web pages is set to text/xml: <meta http-equiv="content-type" content="text/xml; charset=utf-8" />I should therefore change the php.ini MIME type to text/xml, right? Hello, I'm having a bit of a problem here, all help to this issues would be much appreciated I am trying to use text boxes to insert numbers into the database based on what is inputed. If I have a string, like this for example: $variable = 09385493; And I want to insert it into the database like this: mysql_query("INSERT INTO integers(number) VALUES ('$variable')"); When checking the integers table in my database, looking at the number field, the $variable that was inserted is outputted as 9385493 Notice the number zero was taken out of the front of the number. If the number is double 0's (009385493), both of those zero's would disappear, too. Thanks Hello, Does anyone know how may i detect the Connection type by user IP? Broadband etc. I have a Form and need to loop through 10 fields on it. Which Looping Structure would be best and why? In PHP, I believe my choices are... - For Each - Do While - While Thanks, Debbie This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=308253.0 Is there any possible way to determine a drive type (e.g., hard disk, dvd drive, usb drive, etc.) and partition type (e.g., NTFS, CDFS, ext3, etc.) in php without the use of COM and importing OS resources? I ask, because I am developing a custom system explorer for a web application. I already know how to detect drives, drive size/usage and associated drive letters, but am curious if any built-in functions of php can do this. Any help is appreciated. |