0

I am creating a school Software in PHP and I have a couple of subject ids which were implored using the implore() function and inserted in the db, delimited by commas(,).I retrieved them and they are a string e.g when I var_dump it's showing that it's a string.

Example:

$subjId = $class_data['subject_ids']; 

var_dump($subjId) // string(6) "9, 4,5,"

Note that it's commas are also counted.

How do I use each number in the string, or convert the string into an integer array? I want to match each number to its respective subject from a subjects table and then output the subject names.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • Is the sujects table a database table, too? Then you don't need to convert the "string numbers" to integers. You just can query like this: SELECT subject_name FROM XY WHERE subject_id = '$number' The database will not care if $number is a integer or a string. – Andreas Aug 08 '22 at 22:27
  • Could be as simple as `array_map('intval', explode(',', $class_data['subject_ids']));` – Guido Faecke Aug 08 '22 at 22:28
  • I tried array_map('intval', explode(',', $class_data['subject_ids'])); it's actually converting all IDs to a single digit number, e.g //945. @Andreas the $class_data['subject_ids'] is a result from a class table, where a user has created a class, and then selected subjects for that particular class. I don't have problems with to echo $class_data['class_name'] because it's a string, but the question above is that I want to further use each number. I tried SELECT from subjects_table WHERE id = $class_data['subject_ids']... Didn't work – Kawana Jacksey Aug 08 '22 at 23:15

1 Answers1

0

It's simple when you have implode() your array into the string $subjId you can use this code to convert it into array of int :

$arrayOfInt = array_map('intval', explode(',', $subjId));

In example :

$subjId = '9, 4,5,';

 $arrayOfInt = array_map('intval', explode(',', $subjId));
 
 var_dump($arrayOfInt);

Result of var_dump :

array(4) {
  [0]=>
  int(9)
  [1]=>
  int(4)
  [2]=>
  int(5)
  [3]=>
  int(0)
}
Inazo
  • 488
  • 4
  • 15
  • For loop in the array you can use foreach for example or array_map. foreach( $arrayOfInt as $key => $value ){ //do what you want } full explain here : https://www.php.net/manual/fr/control-structures.foreach.php – Inazo Aug 09 '22 at 12:41
  • Help me to loop through that array, because it's been converted into a single block number when you remove the commas (,) – Kawana Jacksey Aug 09 '22 at 12:54