PHP Output Analysis - php

<?php
$data="98.8degrees";
(double)$data;
(int)$data;
(string)$data;
echo $data;
?>
I was surprised/confused when the actual output was 98.8 degrees
I thought when $data uses (double), it converts to 98.8.
Then when moving to (int), it becomes 98 and forth
But I guess my analogy is wrong. Can someone explain to me how the output became like that?

Doing
(double)$data;
(int)$data;
(string)$data;
just return the double, int and string values but they don't change. To change them, you need to do assign the return values to the actual variable like this:
$data = (double)$data;
$data = (int)$data;
$data = (string)$data;

You keep casting it, but turn around and discard the results. The value in $data never changes. Try the settype() function.

What you probably meant to do was:
<?php
$data="98.8degrees";
$data=(double)$data;
$data=(int)$data;
echo $data;
?>
If you don't keep the result of your operations, you won't see the result of your operations...
Oh - and I have no idea what you hoped to achieve with the
(string)$string;
statement, since it's unclear if/how you ever defined $string...

Related

Want Program logic in PHP To display string

I am having input as Word "CODE"
and I want to get output as "CCOCODCODE"
Please help me with the logic to print this output.
Thanks.
It's rather simple. Looking at your pattern, you need to concatenate all possible prefixes of CODE one after the other. So, maintain a result variable and keep concatenating substrings with 0 as the start point and end point being each index in the string.
<?php
$str = 'CODE';
$result = '';
for($i=0;$i<strlen($str);++$i){
$result .= substr($str,0,$i+1);
}
echo $result;
Try to avoid loops whenever you can.
Short and simple does the trick :-)
<?PHP
$Text = 'CODE';
echo implode(array_map(function($Position) use ($Text) { return substr($Text,0,$Position+1); },array_keys(str_split($Text))));

isset strange behaviour and handling function returned data

Could anyone please explain to me why the following line of code prints out true?
$a = "string";
if(isset($a['error'])) echo true; else echo false;
When I do a function call, I return the expected data if it worked properly, or return array("error" => $error);
Then on receiving the returned data I check if isset($var['error']) and if its not then I know I received some expected data.
I would also appreciate if you could advice me if this a good or bad way of handling data between function calls? And if there is a better "good practice" for this.
Well, this is some of PHP misbehaviors, which luckily has been fixed in some recent version.
You can address a single character in a string using the same square braces used to address an array element.
'error' evaluates to 0 and then you have got $a[0] which is set.
to fix that you have to check if $a is array first
I believe it's a bug and it's fixed in PHP 5.4+: http://codepad.viper-7.com/fz1rnT
looks like isset($str[$key]) in same way as isset($str[intval($key)]), where $str and $key are strings
To handle errors best approach are exceptions:
http://php.net/manual/en/language.exceptions.php
I'm not 100% sure why the behavior is like this, but I do know that PHP allows you to handle strings in a similar way as an array.
$a = "StackOverflow";
echo $a[2]; // a
echo $a[4]; // k
echo $a[6]; // v
echo $a[8]; // r
Now when you pass a string key as an index of the array, PHP will try to parse that string into a numerical value to use as a key.
echo $a['stack']; // S
echo $a['over']; // S
echo $a['flow']; // S
echo $a['0stack']; // S
echo $a['1over']; // t
echo $a['2flow']; // a
echo $a['3flow']; // c
echo $a['4flow']; // k

date time comparison in php

i have two time values as give below
$row2[0]=00:40:00;
$row1[5]=14:00:00;
$time=14:33:00
$time=$row[1];
i am combining $row2[0],$row1[5] like below
$secs = strtotime($row2[0])-strtotime("00:00:00");
$result = date("H:i:s",strtotime($row1[5])+$secs);
$result=14:40:00
i use if condition as shown
if($row[1]>$row1[5] && $row[1]<$result)
{
$message=array("status"=>$result);
}
else
{
$message=array("status"=>'');
}
but i get "status"=>"" its not correct
i want to get "status"=>"14:40:00"
please help us for getting correct out put
You don't appear to define $row[1] anywhere, so it is treated as NULL, which as an integer is 0, which cannot be greater than the time you have given in $row1[5].
Try using less ambiguous variable names, it might make it easier to spot problems like this.
Personally I don't see why that if is there at all, just remove it and the else block, leaving just $message = array("status"=>$result);.
is this real oder pseudo code ?
because
$row2[0]=00:40:00;
is not real php code !
$row2[0] = 00:40:00; // $row2[0] would be 0, because you are assigning an integer
$row2[0] = "00:40:00"; // $row2[0] would be "00:40:00", but as a string (!)
i would always work with timestamps btw.
I go with Panique on his answer, I want to add also:
You declared two vars:
$row2[0]=00:40:00;
$row1[5]=14:00:00;
But you called different array elements in the if
if($row[1]>$row1[5] && $row[1]<$result)
Solve this and you should have your code working.

Getting the integer from this php function that shows how many elements are being viewed?

I got this function:
<?php bbp_get_topic_pagination_count(); ?>
and the final output is something like this:
Viewing 10 replies - 1 through 10 (of 13 total)
I would like to just get (filter) the "total" (13 in the example above).
Any suggestions?
Something like this?
function custom_function() {
global $bbp;
return bbp_number_format( $bbp->reply_query->found_posts );
}
function custom_bbp_get_total() {
global $bbp;
$total = bbp_number_format( $bbp->reply_query->found_posts );
return $total;
}
It looks like this number is fetched from $bbp->reply_query->found_posts. Just use that expression. (Make sure to issue global $bbp; if you are going to fetch the value from inside a function.)
Well just a wild guess but given that $bbp is a global, and assuming that it isn't altered in any detrimental way as a side effect of executing that function, you should be able to copy exactly what is assigned to $total in the function, i.e. you can get the value like this:
$total = $bbp->reply_query->found_posts;

Can this be done in 1 line?

Can this be done in 1 line with PHP?
Would be awesome if it could:
$out = array("foo","bar");
echo $out[0];
Something such as:
echo array("foo","bar")[0];
Unfortunately that's not possible. Would it be possible like this?
So I can do this for example in 1 line:
echo array(rand(1,100), rand(1000,2000))[rand(0,1)];
So let's say I have this code:
switch($r){
case 1: $ext = "com"; break;
case 2: $ext = "nl"; break;
case 3: $ext = "co.uk"; break;
case 4: $ext = "de"; break;
case 5: $ext = "fr"; break;
}
That would be much more simplified to do it like this:
$ext = array("com","nl","co.uk","de","fr")[rand(1,5)];
Why not check out the array functions on the PHP site?
Well, if you're picking a random element from the array, you can use array_rand().
$ext = array_rand(array_flip(array("com","nl","co.uk","de","fr")));
echo array_rand(array_flip(array('foo', 'bar')));
array flip takes an array and swaps the keys with the values and vice versa. array_rand pulls a random element from that array.
You can use a shorthand form to keep things on one line and avoid creating an array that will never be used again.
echo rand(0,1) ? rand(1,100) : rand(1000,2000);
Yes, list a PHP language construct that allows the syntax below.
list( $first_list_element ) = array( "foo", ..... );
EDIT:
Still Yes, Missed the echo. Reset will return the first array item, which might not always be index 0, but if you create an array normally it will.
echo reset( array( "foo",... ) );
EDIT AGAIN:
After you updated your question I see that you want something that PHP just can't do well. I personally think it's a syntax design error of the PHP language/interpreter. If you just mean one-line you could do.
$array = array( .... ); echo $array[0];
I think your example may not be the best. The real syntax limitation here is that one can not immediately perform array access on the returned value of a function call, as in,
do_something_with(explode(',', $str)[0]);
And you pretty much can't get around it. Assign to a variable, then access. It's a silly limitation of PHP, but it's there.
You can technically do,
function array_access($array, $i) {
return $array[$i];
}
do_something_with(array_access(explode(',', $str), 0));
But please don't. It's even uglier than an extra variable asignment.
(Given the edit to the question, this no longer a sufficient answer. However, I will leave it up for reference.)
Like #Matchu's answer, this addresses the more general case, ie you have an array value that came from somewhere, be it a function call, an instantiated array, whatever. Since the return value from an arbitrary function is the least specific case, I'll use a call to some_function() in this example.
$first_element = current(array_slice(some_function(), 0, 1));
So you could randomize it with
$random_element = current(array_slice(some_function(), rand(0,1), 1));
but in that case (as in many in php) there is a more specialized function for that; see #animuson's answer.
edited
changed array_shift() call to current() call: this is more efficient, because array_shift() will modify the intermediate array returned by array_slice().
This is being discussed in the internals mailing list right now. You might want to check it: http://marc.info/?l=php-internals&m=127595613412885&w=2
print $a[ array_rand($a = array('com','nl','co.uk','de','fr')) ];

Categories