learn

String Pad

category: Snippets
Created by: Assaad Youssef Abou-Rached

String Pad

category: Snippets
Created by: Assaad Youssef Abou-Rached
twitter google+ facebook pin 

String Pad

Just recently I was working on an Inventory Control web application that deals with different types of items and products, including
in-store items (vegetables, fruits, meat, etc - items that do not have a barcode).
Each in-store item must have a PLU number that consists of 5 numbers, and the 5 numbers must be present even if the PLU number for item X is 1. So what I needed to do is to precede PLU 1 with 4 zeros 00001. But how can I tell PHP to add 2 zeros to PLU 345?
Easy, we simply use the amazing PHP built-in str_pad().
Say that you want your codes consist of 5 numbers at maximum and 1 number at minimum and must be preceded with ZEROS.

The first line will output: 00013
The second line will output: 00001
As expected.

Now lets explain how str_pad() works.
As shown, str_pad takes in your input variable, $plu1 for example, as a first argument. The second argument is the pad length.
The third argument takes the pad strings (0 in our case). And the fourth argument is a constant variable that tells PHP where
you want you pad your string (right, left, or both) [STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH]

The following code will output ***PHP Win***
The input string will be "PHP Win" (7 characters including space), so to have 3 stars padded to each side we will have to use 13
as the string pad (13 - 7 = 6)