He has x number of friends.
If he were to give each friend 3 marbles, he would still have 7 marbles left, so he has 3x + 7 marbles.
If he were to give each friend 5 marbles, he would be 9 marbles short, so he has 5x - 9 marbles.
Since the total number of marbles is the same in both instances, 5x - 9 = 3x + 7.
(5x - 9) - 3x = (3x + 7) - 3x
2x - 9 = 7
2x - 9 + 9 = 7 + 9
2x = 16
2x / 2 = 16 / 2
x = 8 he has 8 friends
verifying:
(3 * 8) + 7 = 24 + 7 = 31 marbles
(5 * 8) - 9 = 40 - 9 = 31 marbles