I want to make simple program that change operators "+", "-", "*", "/" for some numbers. So, I put operators in array, and try to iterate them through loop.
$num1 = 10;
$num2 = 20;
$operators = array("+", "-", "*", "/");
for ($x=0;$x<=count($operators)-1;$x++){
echo $num1 . $operators[$x] . $num2 . "</br>";
}
It displays:
10+5
10-5
10*5
10/5
That seems ok, at first glance, but I need numbers to be calculated, operations performed, simply, I need final result numbers, and this gives me 4 strings. I understand reason for this: my values in $operators array are strings, not real operators. My question is, how to put real operators in array, or maybe, I can keep them as strings in array, but somehow convert them in real operators at the output? Solutions for both strategies are welcome. Thanks in advance!
perhaps you could try somehting along the following lines:
for ( $x=0; $x < count($operators); $x++ ){
switch($operators[$x]){
case '+':$answer=$num1+$num2;break;
case'-':$answer=$num1-$num2;break;
case '*':$answer=$num1*$num2;break;
case'/':$answer=$num1/$num2;break;
}
echo $answer;
}
You can't put real operators in array as it's language contructions. But you can put functions like that (I use anonymous functions, you can use named)
$operations = array(
'+' => function ($a, $b) { return $a + $b; }
);
foreach ($operations as $sign => $func) {
echo '10'.$sign.'5 = '. $func(10, 5)."\n";
}
You may try this
$num1 = 10;
$num2 = 20;
$operators = array("+", "-", "*", "/");
for ($x=0;$x<=count($operators)-1;$x++){
echo eval('return '.$num1 . $operators[$x] . $num2 . ';')."</br>";
}
Related
i want to get the count of some text that starts with specific letter with "/"
just like as follows. i want the count of all "A/" occurancves in that array.
<?php
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
$count_A = count($arr_vals,"A/*");
?>
Simple and easy one..Here is your solution:-
$input = preg_quote('A/', '~'); // don't forget to quote input string!
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
$result = preg_grep('~' . $input . '~', $arr_vals);
echo count($result); die;
array_reduce can be used to take your entire array and compute a result, through the use of a callback function. We can use regular expressions to define what your pattern is. Combining these two things, we have your solution:
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
function match($carry, $item) {
return $carry + preg_match('/A\/./', $item);
}
var_dump(array_reduce($arr_vals, 'match', 0)); // Returns 4
Using fnmatch would also work and uses shell wildcards, e.g. * and ?:
function count_pattern(array $input, string $pattern): int {
$count = 0;
foreach ($input as $string) {
$count += fnmatch($pattern, $string);
}
return $count;
}
Usage
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
echo count_pattern($arr_vals, "A/*"); // 4
Note: in order to use scalar type hints and returns you need PHP7. If you are not on PHP7 yet, you can just omit them.
Yes the correct answer is
$input = preg_quote('A/', '~'); // don't forget to quote input string!
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
$result = preg_grep('~' . $input . '~', $arr_vals);
echo count($result); die;
How to merge two words together letter by letter in php on the following way:
Input #1: Apricot
Input #2: Kiwi
Expected output: AKpirwiicot.
So that if one word's characters are more than the other, it simply writes it down until the end.
I tried it by this logic:
Input smthing
str_split()
array_merge()
But I failed. Any solutions appreciated.
$string1 and $string2 can be in any order.
$string1=str_split("Apricot");
$string2=str_split("Kiwi");
if(count($string2)>count($string1)){
$templ = $string1;
$string1 = $string2;
$string2 = $temp;
}
$result = "";
foreach($string1 as $key => $var){
{
$result.=$var;
if(isset($string2[$key])){
$result.$string2[$key];
}
}
echo $result;
Array_merge() also sticks one array on the end of the other so it wouldn't do what you are looking for I believe.
edit : ive adjusted to take into account no order, like #nikkis answer.
How about this:
def str_merge(a, b):
s = ''
k = min(len(a), len(b))
for i in range(k):
s += a[i] + b[i]
s += a[k:] + b[k:]
return s
In PHP:
function merge($a, $b)
{
$s = '';
$k = min(strlen($a), strlen($b));
for($i=0; $i<$k; $i++)
{
$s = $s . $a[$i] . $b[$i];
}
$s = $s . substr($a, $k) . substr($b, $k);
}
Please forgive my PHP, not my strongest language...
using php. I have the following number
4,564,454
454,454,454
54.54
65.43
I want to convert these into number for calculating. How can I do it? Right now, the type of these number is string.
Note: the comma is not a separate of a number, it is a notion to make a number nicer. I got this format from the ajax request, I cant change the format though. So, I have to use it.
Thanks
$var = floatval(str_replace(",", "", "454,454,454"));
$a='4,5,4';
$ab= explode(',', $a);
foreach ($ab as $b)
{
$sum+=$b; //perform your calculation
}
echo $sum;
First you need to remove ,(comma) from your string as below :
$str=str_replace(",", "", "454,454,454");
Then converting in numeric:
$int = (int)$str;
or
$int=intval($str);
now do your calculation using $int variable.
try this code
$str = '4,564,454';
$str2 = '454,454,454';
$str3= '54.54';
$str4= '65.43';
$sum=0;
$sum += array_sum(explode(',',$str));
$sum += array_sum(explode(',',$str2));
$sum += $str3;
$sum += $str4;
echo $sum;
Having used Java for a long time my standard method for creating long strings piece by piece was to add the elements to an array and then implode the array.
$out[] = 'a';
$out[] = 'b';
echo implode('', $out);
But then with a lot of data.
The (standard PHP) alternative is to use string concatenation.
$out = 'a';
$out .= 'b';
echo $out;
To my surprise there seems to be no speed difference between both methods. When there is significant time difference usually it is the concatenation that seems faster, but not all of the time.
So my question is: are there - apart from style and code readability - any other reasons to choose one approach over the other?
To me, using an array implies that you're going to do something that can't be done with simple string concatenation. Like sorting, checking for uniqueness, etc. If you're not doing anything like that, then string concatenation will be easier to read in a year or two by someone who doesn't know the code. They won't have to wonder whether the array is going to be manipulated before imploded.
That said, I take the imploded array approach when I need to build up a string with commas or " and " between words.
Choose the more readable one. Always. This case, i would pick up the second apporach.
Then optimize it, if it's a bottleneck.
One (subtle) difference is clearly visible when generating a character-seperated string:
<?php
$out[] = 'a';
$out[] = 'b';
echo implode(',', $out);
foreach($out as $o) {
echo $o . ',';
}
?>
The first one will print a,b where the latter will print a,b,. So unless you're using an empty string as a seperator, as you did in your example, it's usually preferred to use implode().
The concatenation-vs-implode holy war aside: No, there is no difference.
Here is a performance test for both approaches:
<?php
const M = 1000000;
// Imploding method
$start = microtime(true);
$arr = [];
for ($i = 0; $i < M; $i++) {
$arr[] = chr(65 + ($i & 0x7));
}
$str1 = implode('', $arr);
$time1 = microtime(true) - $start;
// Concatenation method
$start = microtime(true);
$str2 = '';
for ($i = 0; $i < M; $i++) {
$str2 .= chr(65 + ($i & 0x7));
}
$time2 = microtime(true) - $start;
assert( $str1 == $str2 );
echo "Time 1: $time1\n";
echo "Time 2: $time2\n";
Output with PHP 7.1.33 on MacOS:
Time 1: 0.121246
Time 2: 0.059228
Output with PHP 8.0.5 on a (slow) Debian:
Time 1: 0.88076496124268
Time 2: 0.8109610080719
So, concatenation method works faster.
it depends on what you want to do with the string / array and how you create it
if you start with an array and need to sort it / manipulate certain elements, then i suggest implode
other than that i usually use concatenation
Is there a way to convert an integer to a string in PHP?
You can use the strval() function to convert a number to a string.
From a maintenance perspective its obvious what you are trying to do rather than some of the other more esoteric answers. Of course, it depends on your context.
$var = 5;
// Inline variable parsing
echo "I'd like {$var} waffles"; // = I'd like 5 waffles
// String concatenation
echo "I'd like ".$var." waffles"; // I'd like 5 waffles
// The two examples above have the same end value...
// ... And so do the two below
// Explicit cast
$items = (string)$var; // $items === "5";
// Function call
$items = strval($var); // $items === "5";
There's many ways to do this.
Two examples:
$str = (string) $int;
$str = "$int";
See the PHP Manual on Types Juggling for more.
$foo = 5;
$foo = $foo . "";
Now $foo is a string.
But, you may want to get used to casting. As casting is the proper way to accomplish something of that sort:
$foo = 5;
$foo = (string)$foo;
Another way is to encapsulate in quotes:
$foo = 5;
$foo = "$foo"
There are a number of ways to "convert" an integer to a string in PHP.
The traditional computer science way would be to cast the variable as a string:
$int = 5;
$int_as_string = (string) $int;
echo $int . ' is a '. gettype($int) . "\n";
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
You could also take advantage of PHP's implicit type conversion and string interpolation:
$int = 5;
echo $int . ' is a '. gettype($int) . "\n";
$int_as_string = "$int";
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
$string_int = $int.'';
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
Finally, similar to the above, any function that accepts and returns a string could be used to convert and integer. Consider the following:
$int = 5;
echo $int . ' is a '. gettype($int) . "\n";
$int_as_string = trim($int);
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
I wouldn't recommend the final option, but I've seen code in the wild that relied on this behavior, so thought I'd pass it along.
Use:
$intValue = 1;
$string = sprintf('%d', $intValue);
Or it could be:
$string = (string)$intValue;
Or:
settype($intValue, 'string');
Warning: the below answer is based on the wrong premise. Casting 0 number to string always returns string "0", making the code provided redundant.
All these answers are great, but they all return you an empty string if the value is zero.
Try the following:
$v = 0;
$s = (string)$v ? (string)$v : "0";
There are many possible conversion ways:
$input => 123
sprintf('%d',$input) => 123
(string)$input => 123
strval($input) => 123
settype($input, "string") => 123
You can either use the period operator and concatenate a string to it (and it will be type casted to a string):
$integer = 93;
$stringedInt = $integer . "";
Or, more correctly, you can just type cast the integer to a string:
$integer = 93;
$stringedInt = (string) $integer;
As the answers here demonstrates nicely, yes, there are several ways. However, in PHP you rarely actually need to do that. The "dogmatic way" to write PHP is to rely on the language's loose typing system, which will transparently coerce the type as needed. For integer values, this is usually without trouble. You should be very careful with floating point values, though.
I would say it depends on the context. strval() or the casting operator (string) could be used. However, in most cases PHP will decide what's good for you if, for example, you use it with echo or printf...
One small note: die() needs a string and won't show any int :)
$amount = 2351.25;
$str_amount = "2351.25";
$strCorrectAmount = "$amount";
echo gettype($strCorrectAmount); //string
So the echo will be return string.
My situation :
echo strval("12"); => 12
echo strval("0"); => "0"
I'm working ...
$a = "12";
$b = "0";
echo $a * 1; => 12
echo $b * 1; => 0
I tried all the methods above yet I got "array to string conversion" error when I embedded the value in another string. If you have the same problem with me try the implode() function.
example:
$integer = 0;
$id = implode($integer);
$text = "Your user ID is: ".$id ;
You can simply use the following:
$intVal = 5;
$strVal = trim($intVal);
$integer = 93;
$stringedInt = $integer.'';
is faster than
$integer = 93;
$stringedInt = $integer."";