PHP $String{0} VS. $String[0];

PHP $string{0} vs. $string[0];

use $string[0], the other method (braces) has been removed in PHP 8.0.

For strings:

Accessing characters within string literals using the {} syntax has been deprecated in PHP 7.4. This has been removed in PHP 8.0.

And for arrays:

Prior to PHP 8.0.0, square brackets and curly braces could be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} would both do the same thing in the example above). The curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.

Why does PHP consider 0 to be equal to a string?

You are doing == which sorts out the types for you.

0 is an int, so in this case it is going to cast 'e' to an int. Which is not parsable as one and will become 0. A string '0e' would become 0 and would match!

Use ===

From PHP.net:

Comparisons between strings and numbers using == and other non-strict
comparison operators currently work by casting the string to a number,
and subsequently performing a comparison on integers or floats. This
results in many surprising comparison results, the most notable of
which is that 0 == "foobar" returns true.

However this behavior was changed in PHP 8.0:

When comparing to a numeric string, PHP 8 uses a number comparison.
Otherwise, it converts the number to a string and uses a string
comparison.

PHP 7

0 == 'foobar' // true
0 == '' // true
4 == '4e' // true (4e is cast as a number and becomes 4)

PHP 8 converts numbers to strings before making comparisons

0 == 'foobar' // false
0 == '' // false
4 == '4e' // false ('4e' is considered non-numeric therefore 4 is cast as a string and becomes '4')

This is a major change therefore it was implemented in a new major PHP version. This change breaks backward compatibility in scripts that depend on the old behavior.

Why would you have a string = '0' condition in PHP?

1. Well, think how the reverse would go.

 $st = strlen($nr);
$sl = $total = 0;
while($sl < strlen($nr) and substr($nr, ++$sl, 1) >='0'){

Notice the strlen in the while loop - bad practice. Although in PHP it's fast, in most programming languages this is horrible for performance. The alternative would be to use another variable, which would be reduntant.

So the best option for both lazyness and performance is to start from the end.

2. As far as I can tell, the only purpose of that string comparison is to make sure the position in the ASCII table is higher or equal to '0' ASCII no. 48). First, check the http://www.asciitable.com/

Then take a look at the following tests I did:

var_dump(' ' >= '0'); // false // space has ASCII no 32
var_dump('(' >= '0'); // false // ASCII no 47
var_dump('A' >= '0'); // true // ASCII no 65
var_dump('[' >= '0'); // true // ASCII no 71

So it's almost an alphanumeric test, as @mudasobwa mentioned.

Getting the first character of a string with $str[0]

Yes. Strings can be seen as character arrays, and the way to access a position of an array is to use the [] operator. Usually there's no problem at all in using $str[0] (and I'm pretty sure is much faster than the substr() method).

There is only one caveat with both methods: they will get the first byte, rather than the first character. This is important if you're using multibyte encodings (such as UTF-8). If you want to support that, use mb_substr(). Arguably, you should always assume multibyte input these days, so this is the best option, but it will be slightly slower.

Find first occurence (position) of number 0 from end of string

Using regex you could use PREG_OFFSET_CAPTURE as follow:

function maximizeNumberRoundness($n) {
$firstZero = strpos($n, "0");
preg_match('/([^0])0*$/', $n, $match, PREG_OFFSET_CAPTURE);

echo "first zero: " . $firstZero;
echo "\r\n";

$last_nonzero_index = strlen($n) - $match[1][1] - 1;

echo "last non-zero: " . $last_nonzero_index;
}

maximizeNumberRoundness(902200100);

Output:

first zero: 1
last non-zero: 2

This works as far as I understand correctly that you want the index of the last non-zero from the right of the string.

Accessing characters in a string using array syntax

Okay, I'll aggregate my comments as an answer:

To quote the manual

Strings may also be accessed using braces, as in $str{42}, for the
same purpose. However, this syntax is deprecated as of PHP 7 .
Use square brackets instead.

Also, albeit undocumented, the {} accessor also works for arrays, which makes $foo{$bar} and $foo[$bar] completely equivalent. It's just old syntax for the convenience of Perl programmers.

Concerning your second question, if it is good practice to treat strings like an array of characters: Yes, if it is useful for your task, do it. In low level languages like C, strings are arrays of characters, so it is quite natural to treat them like that.

BUT keep in mind that PHP has bad unicode support. So if your string is in multi-byte encoding (ie UTF-8), this might not work as expected. Better use the multibyte functions in that case.

0' as a string with empty() in PHP

You cannot make empty() take it. That is how it was designed. Instead you can write an and statement to test:

if (empty($var) && $var !== '0') {
echo $var . ' is empty';
}

You could use isset, unless of course, you want it to turn away the other empties that empty checks for.

Remove all zero values from string PHP

here's a nice algo:

<?php

$string = "14522354265300000000000";
$new_string = '';
for($i=0; $i<strlen($string) ; $i++){
if($string[$i] != '0'){
$new_string .= $string[$i];
}
}

echo $new_string;

?>

rtrim is only if you have zero's at end of string :)

What does mean by 'out of range offset' and when does 'only the first character of an assigned string is used'?

This part of the manual is in reference to treating strings as an array of characters.

  • "out of range" offset means an integer index that is at a position longer than the string itself currently is, e.g. $x = "foo"; $x[10] = 'o'; results in $x becoming foo o

  • If a non-integer index value is used, the index value is converted to an integer before the index of the string is accessed, e.g. $x = "foo"; $y = $x[true]; results in $y taking the value of $x[1] - o

  • Illegal offset types are anything that couldn't normally be used as an array offset, e.g. class Foo() {} - indexing a string with $x[new Foo()]; raises a warning

  • The first chracter piece means that if you attempt to assign a string to the index of an existing string, only the first character of the assigned string will be used, e.g. $x = "foo"; $x[0] = "hi"; results in $x becoming hoo;

  • Assigning a string a value of empty string at an index now results in an error rather than assigning the "null" byte \0, e.g. $x[0] = ''
    will fatal.



Related Topics



Leave a reply



Submit