user2371301
user2371301

Reputation: 3474

Display first 4 digits of id column from mysql table

I have a session that pulls information from a database

<?php session_start(); echo $_SESSION['id']; ?>

I am wanting to display a "shorter" version of this id as a "short id" in the webpage. the id is 16 digits long I want to only display the first 4 digits.

I tried

<?php session_start(); echo $_SESSION['id']-12; ?>

But it only gave me a weird number like this:

5.3830822562889E+15

The original id is: 5383082256288945 so I am wanting to display: 5383

Upvotes: 2

Views: 791

Answers (3)

hrr
hrr

Reputation: 1651

You should use substr

<?php session_start(); echo substr($_SESSION['id'], 0, 4); ?>

Upvotes: 4

pinkpanther
pinkpanther

Reputation: 4798

Use substr function in php. The second parameter is start index, if it is negative start counting it from the end, and the second parameter is the length of the sub string you need.

echo substr('5383082256288945', 0, 4); gives you 5383.

See here for docs: PHP Substring Manual

In your case:

<?php session_start();
   $id=substr($_SESSION['id'],0,4);
   echo $id;
 ?>

From PHP docs:

<?php
echo substr('abcdef', 1);     // bcdef
echo substr('abcdef', 1, 3);  // bcd
echo substr('abcdef', 0, 4);  // abcd
echo substr('abcdef', 0, 8);  // abcdef
echo substr('abcdef', -1, 1); // f

// Accessing single characters in a string
// can also be achieved using "square brackets"
$string = 'abcdef';
echo $string[0];                 // a
echo $string[3];                 // d
echo $string[strlen($string)-1]; // f

?>

Upvotes: 3

kraysak
kraysak

Reputation: 1756

$id=5383082256288945;
$rest = substr($id, 0, 4);
echo $rest;

Check substr for more information.

Upvotes: 1

Related Questions