1

I am creating a website for school.

I have the subjects of a student saved in a database.

It's get saved like this --> 1,2,3,6,7

This means student X does subject ID 1,2,3, 6 and 7

The subjects from one student get returned from a database in one variable $subjects I would like to output the Subject Name (subject names are also stored in the database). But since the variable that is returned in $subjects is not one subject, but multiple, I can't search for the subject name. Is it possible to convert $subjects to an array so that $subjects[0] would be 1 in my example and $subjects[1] would be 2 (see above @ it's get saved like this).

Simply said: it should not be $subjects = 1,2,3,6,7 but

$subjects[0] = 1
$subjects[1] = 2
$subjects[2] = 3
$subjects[3] = 6
$subjects[4] = 7
3
  • 2
    explode() Commented Aug 28, 2013 at 20:42
  • 3
    You can get the database itself to give out the names directly, but for this to happen you must normalize the schema by creating a join table for the N-to-M relationship between students and subjects. Google a bit. Commented Aug 28, 2013 at 20:43
  • @Carsten That seems to do it! Thanks man! Commented Aug 28, 2013 at 20:44

2 Answers 2

2

You can use explode to convert a string to an array:

explode(',', $students);

It should be noted, however, that exploding and then doing more queries to your database to get the subject names is a very inefficient way to do this. Rather that store students subjects in one field you should create a whole table for that relationship. So in additional to a Students table and a Subjects table, you have the relationship:

Table: StudentSubjects

Student | Subject
-----------------
   1    |   1
   1    |   2
   1    |   3
   1    |   6
   1    |   7
   2    |   2
   2    |   4
   2    |   6
   2    |   8
   3    |   3

Then you can query your database and get a list of subject names for a particular student, or group of students, in one query.

Sign up to request clarification or add additional context in comments.

Comments

0

You can choose 2 way:

explode :

<?php
$str = '1,2,3,6,7';
$chars = explode(',', $str);
print_r($chars);
?>

or preg_split:

<?php
$str = '1,2,3,6,7';
$chars = preg_split('/,/', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>

1 Comment

There is no reason to use preg_split when explode will suffice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.