Possible Bug, Possibly me being stupid ;)


#1

Stuck At: https://www.codecademy.com/courses/web-beginner-en-7I7Xm/0/2?curriculum_id=5124ef4c78d510dd89003eb8#

I do not have any error messages, and can proceed if necessary, but I couldn’t find the bug report section so I figured I’d write this here.
Now the bug in question, if you look at my code below, for the sub string, I provide code to fetch the string from characters 0-3, however it goes from 0-2. If my memory is correct, when a string character is assigned a place it starts at 0, so “Nick” is:
N= [0]
i= [1]
c=[2]
k=[3]
When I change the end character value from substr($test, 0, 3); to substr($test, 0, 4); it extends to print the full string – print strlen($test) the output would be 4, because the string is 4 characters in length, however if it were to start counting at zero, then the last character in the string should be assigned a character place of the string length minus one right?

EDIT: Note, the only explanation, in my mind, is that, you know when someone is to say, ‘pick a number between one and ten’ you don’t really pick 1 or 10, I get the concept, but at the same time if I set print substr($test, 1, 4) it will output “ick” meaning that the N is assigned a place value of 0, but then why is the k assigned a place value of 4?

```

<?php $test="Nick"; print substr($test, 0,3); ?>

<?php print strtoupper($test); ?>

<?php echo strtolower($test); ?>

<do not remove the three backticks above>

#2

Actually, the length of substr is the number of characters you want. You asked for 3 characters in total starting at the offset of 0. Therefore, you’d receive Nic which is characters: 0-2 for a total of 3 characters:

Nick where:
N is the character at position 0
i is the character at position 1
c is the character at position 2
k is the character at position 3

From the PHP manual, let’s break it down for you:

http://php.net/manual/en/function.substr.php

string substr ( string $string , int $start [, int $length ] )

$start is where you want to start in the string you are working on. Remember, it’s 0 based index.

$length is the number of characters you want. For example, if you only want one character, then you put 1 as the length.

  • A position length begins where at the $start. Then it’s the number of characters from that index position.

  • A negative length omits those positions from the end of the string.

Remember, the length of 4 means: give me 4 characters starting at the start position.

substr($test, 0, 4); means give me 4 characters starting at position 0. The result is Nick. Right? It started at position 0 which is the N and then gave you 4 characters.


#3

Ah, that would make more sense, I misinterpretted 4 as the end numeric place value rather than the length, than you for clarifying!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.