How do I split a numerical query result? [closed] - php

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm pulling an id number from a database where it is stored as 12345
When I display it on my page (php), I'd like to have it show up as 1-2345
Can I do this without using Javascript? If so, how?
Thanks!
ETA: it's part of a loop of data that is pulled dynamically, so the number is always different. I need to be able to tell it to put a dash after the first number. It's not necessarily 1-2345; it's more X-XXXX (where X is a random number).

You should be able to use the following in MySQL:
select
concat(left(yourCol, 1),
'-',
right(yourcol, length(yourCol)-1)) YourValue
from yourtable
See SQL Fiddle with Demo
This implements the following MySQL functions:
CONCAT
LEFT
RIGHT
LENGTH
Or you can use SUBSTR instead of RIGHT and LENGTH:
select
concat(left(yourCol, 1),
'-',
substr(yourcol, 2)) YourValue
from yourtable;
See SQL Fiddle with Demo
SUBSTR

In PHP
$id = (str)$dbVal;
$str = $id[0]."-".substr($id, 1, strlen($id) - 1);
echo $str;

$var = "12345";
echo $var[0] . "-" . substr($var,1);
This should work for values of any length.

First, use your SELECT MySQL command to find your ID number.
Let's say $string is actually the 'stringified' version of the ID.
$string = "12345";
$string = str_replace($string[0], $string[0] . "-", $string);
echo $string;

The other answers don't address where to put your code, and why. Inserting a dash after the first digit is display-related logic, and display-related logic belongs in the template. It certainly doesn't belong in the database layer. You could put the actual code right alongside the HTML, but that would be a) probably not very intent-revealing and b) not very reusable.
For the best separation of concerns, I would first define a "helper" function like this, in its own file:
function insert_dash_after_first_number($value)
{
return str_replace($value[0], $value[0].'-', $value);
}
Then, in your template, you can do this (granted you included the helper file):
<?php echo insert_dash_after_first_number('12345'); ?>
Hopefully you can see that separating things in this way would make it pretty clear to others and your future self what's going on. You can just look at the function name and see "oh, this inserts a dash after the first number". You don't have to look at any code and think about what it might do.

$string1 = substr($id, 0,1);
$string2 = substr($id, 1, strlen($id));

Related

How can I use php function mb_convert_case and convert only certain words to upper?

I want to pass this input
$string = "AL & JRL buSineSS CENTRE is the best";
Expected Result:
AL & JRL Business Centre Is The Best
I have tried the code below but it converts everything.
mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
So I take it you just want potential acronyms to be ignored, correct? Well, there are a few thoughts. First, you could make a script that ignores anything with 3 or less letters. That's not a great solution, in my opinion. What about "it", "the", etc.? The second is using a dictionary of known words to run ucwords() on. Yuck - that'd be incredibly taxing for such a seemingly simple task!
I'd recommend simply ignoring anything that is all-caps. This way, no matter what the acronym is (or the length), it'll ignore it. Something like this may suffice:
$phrase = "Hello this is a TeSt pHrAse, to be tested ASAP. Thanks.";
$chunks = explode(" ", $phrase);
$result = "";
foreach($chunks as $chunk){
if(!ctype_upper($chunk)) {
$result .= ucwords($chunk) . " ";
} else {
$result .= $chunk . " ";
}
}
$result = rtrim($result);
Result:
Hello This Is A Test Phrase, To Be Tested ASAP. Thanks.
This isn't the most elegant solution, this is just something I've kind of thought about since reading your question. However, if you know your acronyms will be capitalized, this will skip them entirely and only title-case your actual words.
Caveats
The example provided above will not work with an acronym joined to a word by a dash, underscore, etc. This only works on spacing. You can easily tweak the above to your needs, and make it a little more intelligent. However, I wanted to be very clear that this may not fulfill all needs!
Also, this example will come up short in your example phrase. Unfortunately, unless you use a dictionary or count string lengths, this is the closest you'll get. This solution is minimal work for a great deal of functionality. Of course, a dictionary with comparisons would work great (either a dictionary of acronyms or words, either way) - but even then it would be very difficult to keep up to date. Names will throw off a dictionary of words safe to change to title-case. Less commonly used acronyms surely won't be in a dictionary of acronyms. There are endless caveats to all solutions unfortunately. Choose what's best for you.
Hope this helps. If you have any further questions please comment and I'll try the best I can to help.
Randomness
One last thing. I used ucwords(). Feel free to use whatever you want. I'm sure you already know the difference, but check this out:
Best function for Title capitlization?
Always good to know exactly what tool is best for the job. Again, I'm sure you know your own needs and I'm sure you chose the right tool. Just thought it was an interesting read that could help anyone stumbling upon this.
Final Thoughts
You could use a combination of the above examples to custom tailor your own solution. Often it's very satisfactory to combine methods, thus reducing the downsides of each method.
Hope this helps, best of luck to you!

Fibonacci Sequence - PHP shortest code possible

I have spent some time trying to execute the Fibonacci sequence to 500 numbers and output to screen in the shortest amount of code possible. This was a learning exercise for me.
I have condensed it from 21 lines down to 12, this is the shortest code I can write that makes this work.. Can anyone show me how I could have made the code even shorter?
I have looked on google for PHP loops, and the while loop seemed to work best.
Are there any other math tricks in PHP I can use to condense this even more?
Normally when I ask a question, I like to show what research I have done into the problem, but since I don't know any keywords to look up for better math or loops, I am not sure what to search..
Code:
$counter = 0;
$first = 1;
$second = 1;
echo $first."<br/>";
echo $second."<br/>";
while ($counter < 500) {
$next = $first + $second;
echo $next."<br/>";
$counter++;
$second=$first;
$first=$next;
}
The research for the shortest code is called "code golf" and there is a whole stack exchange site devoted to it.
In particular, your question is answered here.
The code is:
<?for($a=$b++;;$b+=$a=$b-$a){echo$a;}
this works by:
removing whitespaces (which are ignored anyway) (cosmetic)
giving variables meaningless names (doesn't affect the output)(cosmetic)
abusing various language features like implicit initialization to zero and multiple assignments
the multiple assignment trick lets you use two variables instead of three (no need for the "current number") exploiting the order of the assignment

In PHP: How do I change lower to upper case in simple string

This is very simple but I need as script where someone from a text field adds a string. The script then counts how many capital A:s there are and how many small a:s there are.
The script should then output number of A:S and a:.s
Thanks very much.
I am not sure if I understand your question. The title is different from the description. If you just want to change from lower to upper there is the PHP function toupper() http://php.net/manual/en/function.strtoupper.php
Some easy googling would have given you your answer.
This is what the first result gave me, it counts the capitals in a string:
function count_capitals($s) {
return strlen(preg_replace('![^A-Z]+!', '', $s));
}
This should be a good start to make your own script which does what you want.

php concatenation parsing errors issue help a newbie [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Please help me with this issue. I am trying to echo out 7 or 8 input types.
The input types must have 2 values from my database.
The Arrays are called : $adressX[] and $adressY. and are automatically loaded when the webpage loads.
So when number is 0 , i want to create a input type with the value : ($adressX[0],$adressY[0]).
I keep getting parsing errors , this being my first project on php/javascript.
Please help me.
My code is like this.
<?php
for ($number=0;$number<=$array_no-1 ;$number++)
{
echo '<input type="text" id="inputtype"."$number"
value="".$adressX['.$number'],".$adressY['.$number']">';
};
?>
You were messing up your quotes and periods. Try this:
<?php
for ($number = 0; $number <= $array_no-1; $number++) {
echo '<input type="text" id="inputtype' . $number . '" value="' . $adressX[$number] . ',' . $adressY[$number].'" />';
}
?>
You should read up on how PHP handles quotes and concatenation, but here are a few examples to get you started.
If you want to start the string with a single quote, you must end/concatenate the string with a single quote as well. Like this:
$var = 'yay';
$string = 'The value of the variable is ' . $var;
$string2 = 'The value of the variable is ' . $var . '!'; // Add another string after variable
Similarly, if you start with double quotes, you have to end/concatenate with double quotes, like this:
$var = "yay";
$string = "The value of the variable is " . $var;
$string2 = "The value of the variable is " . $var . "!";
$string3 = "The value of the variable is $var!";
Notice the last example, $string3. When using double quotes, you can put variables inside the quotes and PHP will still parse them; however, I don't condone this and I ALWAYS concatenate so when using an IDE with syntax highlighting it is obvious where the variables are.
Here is an example of putting the same type quotes in the string that you start/end the string with. To do this, you must use a slash () to tell PHP that these should be parsed as regular quotes instead of delimiters.
$string = 'You\'re using escaped quotes now!'; // notice the \ in front of the ' in you're
Lastly, here is an example of an HTML string in PHP. I usually start these strings with single quotes so that I can use the conventional double quote delimiters for the HTML.
$html = '<div class="someClass">Hello world!</div>';
<?php
for ($number=0;$number<=$array_no-1 ;$number++) {
echo '<input type="text" id="inputtype'.$number'" value="'.$adressX[$number].','.$adressY[$number].'">';
}
Using PHP's echo and print statements is usually where new PHP programmers go to for getting output to the screen. However, when dealing with the output of HTML markup, escaping out of quotes and syntax problems can creep up really quickly. Instead, try using sprintf to format these more complicated markup elements. Here's an example.
for ( $number = 0; $number <= $array_no - 1; $number++ )
{
echo sprintf( '<input type="text" id="inputtype%u" value="%s,%s"/>', $number, $addressX[ $number ], $addressY[ $number ] );
}
The essential things to know is that, at it's essence, sprintf is a complicated kind of search and replace with formatting method. The first argument is a string with placeholders and all of the following arguments are the variables that will be used in that string to replace the placeholders. The number of parameters that follow the input string must match the number of placeholders in your string.
You'll notice %s and %u in the input string that's used in my example. Those mean format as a %s String or as an %u Integer. There are a LOT more ways for format stuff, but, as a novice, these are the ones you'll probably find yourself using the most.
How is this any easier?
It's easier because you can us a properly formatted HTML snippet with double quotes and just add in placeholders. Visually, I find it much more easy to read than a ton of ' . $variable . ' bits scattered throughout your code.
Besides, sprintf is going to become something you use regularly as you move up the PHP ladder. Time to learn it.

"if" statement is ignored [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
There is probably a very simple fix to this, but i'm all new with php, and very ignorant.
I've been trying to get my head around this problem, but to no avail.
Here is the code :
echo $slot['slot_type'];
echo "<br><br>";
if ($slot['slot_type']='tree') echo "This place is full of life, and can be used for hunting, gathering, logging, or other activities.";
if ($slot['slot_type']='town_hall') echo "The town hall houses the governors, and is propriety of the King.";
if ($slot['slot_type']='farm1') echo "Townspeople attempt to grow a selection of wild plants on these crops, hoping for a steady food supply.";
if ($slot['slot_type']='farm2') echo "Farming is hard work, but a full storehouse of food is a great comfort.";
The first line with echo $slot['slot_type']; was my attempt to try and understand why my "if" statement does not work. However, it prints the proper string, in this case "tree".
So, in practise, instead of printing one of the proposed text strings, the browser prints all four of them, as if it ignored my IF statements completely. Again, sorry for asking what looks like such a silly question.
You need to use it like this:
if ($slot['slot_type']=='tree')
You are inserting the values into $slot['slot_type'] instead of comparing.
You need to change all your single = to == or some other logical check.
What you are essentially doing is assigning $slot['slot_type'] the values on the right hand side of your condition which will always return true.
Have a read of the php manual here http://uk.php.net/manual/en/language.operators.php
As an aside, your if structures might be better created using a switch statement.
You're using the assignment operator, =, in your if statements. You should be using the comparison operator, ==.
An elaboration on how this works: the if statement will evaluate the condition given to see if it matches. With your current assignment operator, the PHP engine will actually complete that command (that is, assign the value tree to your slot_type), which returns true since the command successfully completed. The rest of the if statement then executes. The same happens for the rest of the if statements (because you're re-assigning values to your slot_type without error), which then also executes the other branches.
Change = to == . This: = is ony for giving variable value (assignment), and this == is for comparing it with something.
My take: always have php.net open in a tab:
http://uk3.php.net/manual/en/language.operators.assignment.php
http://uk3.php.net/manual/en/language.operators.comparison.php
CASE 1: = (assignment)
$var = 'hello';
CASE 2: ==
equality after type juggling
if(0 == "a") {
print("hi");
}
* will print "hi" because string "a" will actually be converted to 0 by PHP
CASE 3: ===
testing for identity (types must be the same)
if(0 === "a"){
print("hi");
}
* will not print "hi" because the two operands are obviously not the same type.
In your case, you want case 2, to test for equality, or you could use case 3.

Categories