Var_dump (strpos ('mrwagon',626));

Why does var_dump (strpos ("mrwagon",626)); output int (1)

Php
Aug.06,2021

look at the core C code implementation of this function:

    if (Z_TYPE_P(needle) == IS_STRING) {
        if (!Z_STRLEN_P(needle)) {
            php_error_docref(NULL, E_WARNING, "Empty needle");
            RETURN_FALSE;
        }

        found = (char*)php_memnstr(ZSTR_VAL(haystack) + offset,
                            Z_STRVAL_P(needle),
                            Z_STRLEN_P(needle),
                            ZSTR_VAL(haystack) + ZSTR_LEN(haystack));
    } else {
        //char
        if (php_needle_char(needle, needle_char) != SUCCESS) {
            RETURN_FALSE;
        }
        needle_char[1] = 0;

        php_error_docref(NULL, E_DEPRECATED,
            "Non-string needles will be interpreted as strings in the future. " \
            "Use an explicit chr() call to preserve the current behavior");
        //char
        found = (char*)php_memnstr(ZSTR_VAL(haystack) + offset,
                            needle_char,
                            1,
                            ZSTR_VAL(haystack) + ZSTR_LEN(haystack));
    }

static int php_needle_char(zval *needle, char *target)
{
    switch (Z_TYPE_P(needle)) {
        case IS_LONG:
            //long
            *target = (char)Z_LVAL_P(needle);
            return SUCCESS;
        case IS_NULL:
        case IS_FALSE:
            *target = '\0';
            return SUCCESS;
        case IS_TRUE:
            *target = '\1';
            return SUCCESS;
        case IS_DOUBLE:
            *target = (char)(int)Z_DVAL_P(needle);
            return SUCCESS;
        case IS_OBJECT:
            *target = (char) zval_get_long(needle);
            return SUCCESS;
        default:
            php_error_docref(NULL, E_WARNING, "needle is not a string or an integer");
            return FAILURE;
    }
}

if the needle parameter provided by you is not a string, the php_needle_char method will be called to convert to the string corresponding to the parameter. In the question, the ASCII letter corresponding to 626 is r .

you can also use chr to see if the output is r .

C source code: https://github.com/php/php-sr.

There is no such value in

ASCII, so why does the chr method convert 626 to r ? Take a look at how the C code is implemented:

int zend_compile_func_chr(znode *result, zend_ast_list *args) /* {{{ */
{

    if (args->children == 1 &&
        args->child[0]->kind == ZEND_AST_ZVAL &&
        Z_TYPE_P(zend_ast_get_zval(args->child[0])) == IS_LONG) {
        // 0xff 0xff255.
        zend_long c = Z_LVAL_P(zend_ast_get_zval(args->child[0])) & 0xff;

        result->op_type = IS_CONST;
        ZVAL_INTERNED_STR(&result->u.constant, ZSTR_CHAR(c));
        return SUCCESS;
    } else {
        return FAILURE;
    }
}

any number, calculated with 0xff, the result will not be greater than 255, which is within the range of ASCII code expression. 626&0xff=114 , which corresponds to r .

Menu