Day: February 23, 2018

Get first character from string php

If you get first character from string using php then you can use some option.

This is simple code which help you.


//Example string.
$text = "This is demo text for test";

// Option 1 get first character
$option1 = $text[0];

//Option 2 first character
$option2 = substr($text, 0, 1);

// sometime special character not work so use this for first character

$option3 = mb_substr($text, 0, 1);

echo "Result: ". $option1."==".$option2."==".$option3;

then result all is same :

Result: T==T==T

If you face any problem then please inform me, i will try to help you


Get first key from associative array ?

If you need to get first index or key from array then you can use simple php function key. This is simple code which give you first key from array.

$data = array(
    14 => "Test14",
    11 => "Test11",
    4 => "Test4",
    12 => "Test12",
    13 => "Test13");
echo "<pre>";
reset($data); // reset — Set the internal pointer of an array to its first element
$first_key = key($data); //key — Fetch a key from an array
echo "First Key: ".$first_key;

then result is:

    [14] => Test14
    [11] => Test11
    [4] => Test4
    [12] => Test12
    [13] => Test13
First Key: 14

If you need any help then please inform me, i will try to help you.