16

I have a database with a row 'genre' this contains all types of genres for the movie seperated by a space like an example of this would be

Animation Comedy Horror

They are all different genres so they need to be pulled out of the database and put in an array based on their genres I originally began coding this:

<?
sql = "SELECT moviename,genre FROM movieHosting";
$query = mysql_query($sql);
$row = mysql_fetch_object($query);
?>

But I soon realized shortly after that every genre is going to be needed to be put in the array seperate if I did

$genreArray = array($row->genre);

But this wont work it would generate an array like

$genreArray = array("Animation Comedy Horror");

But it needs to generate

$genreArray = array("Animation","Comedy","Horror");
  • 4
    STOP USING mysql_* ! use mysql**i**_* instead !! – Halayem Anis Mar 14 '16 at 16:03
  • 1
    Possible Duplicate of [Splitting up a string in PHP with every blank space](http://stackoverflow.com/questions/5020202/splitting-up-a-string-in-php-with-every-blank-space) – Tushar Aug 22 '16 at 11:54
  • Also see [php explode: split string into words by using space a delimiter](http://stackoverflow.com/questions/18638753/php-explode-split-string-into-words-by-using-space-a-delimiter) – Tushar Aug 22 '16 at 11:55

8 Answers8

28

Have you tried using the explode function?

Something like:

$genreArray = explode(" ", $row->genre);
Chief Wiggum
  • 2,784
  • 2
  • 31
  • 44
  • 6
    I would recommend this over the preg_split function. Cleaner, simpler to look at and quicker. On another note, why not normalize your database a little for efficiency with a one-to-many relationship? – Simon Mar 08 '16 at 10:22
  • STOP USING mysql_* ! use mysqli_* instead !! – Halayem Anis Mar 14 '16 at 16:08
  • What @Simon means is you should not be storing multiple pieces of data as one field. Each genre is its own piece of data. If movies can have multiple genres, you should be moving genres out to a separate table with the following fields: `id`, `movie_id`, `genre_name` or similar. – Marcus Harrison Aug 22 '16 at 10:49
  • Then, instead of having to do text processing in PHP, you can just ask the database for e.g. `('SELECT genre_name FROM genres WHERE movie_id = ?', $movie_id)`. This has additional benefits in the long run, for example, allowing you to find all movies in the `Horror` genre very easily. – Marcus Harrison Aug 22 '16 at 10:52
5

Here is more close to your logic.

$string = 'Animation Comedy Horror';
    $genra = explode(" ", $string);
    print_r($genra); //Array ( [0] => Animation [1] => Comedy [2] => Horror )

    echo $genra[0]; //Animation

    echo '<hr>'; // OR

    foreach($genra as $value){
        echo $value . '<br>';
    }

// Output
Animation
Comedy
Horror

Hope our answers brings more clarification to your problem.

Ulysses
  • 187
  • 2
  • 17
  • 1
    I really like this :) gives a really nice example of what can be done however somebody has already given me what i need an answered it first so all i can give you is an upvote :) –  Mar 11 '16 at 04:25
  • 1
    Thank you for recognizing my answer @Joseph Flames I agree that JamesBlond has the best and simplest answer. ^_^ – Ulysses Mar 11 '16 at 09:41
  • 1
    i upvote because your answer is correct and to be an SO fanatic :) – Halayem Anis Mar 14 '16 at 16:07
  • Thanks @HalayemAnis ^_^ – Ulysses Nov 22 '16 at 06:24
4

Understand these and use accordingly.

<?php
    $str = "Animation Comedy Horror";
    $str_arr = explode(' ', $str);
    print_r($str_arr);
    $str_arr = split(' +', $str);
    print_r($str_arr);
    $str_arr = preg_split('/ +/', $str);
    print_r($str_arr);
?>

Check This : https://eval.in/532527

Also Understand about,

explode : http://php.net/manual/en/function.explode.php

preg-split : http://php.net/manual/en/function.preg-split.php

split : http://php.net/manual/en/function.split.php

split is depricated now.

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
3
   $result = preg_split("/[\s,]+/", "Animation Comedy Horror");
    print_r($result );
    print_r(implode(",",$result));

OUT PUT

 Array ( [0] => Animation [1] => Comedy [2] => Horror ) 

 Animation,Comedy,Horror
channasmcs
  • 1,104
  • 12
  • 27
3

WARNING
Stop using mysql_* functions, for multiple reasons : completely removed, officially deprecated, ... and for exhaustive list you can read this thread Why shouldn't I use mysql_* functions in PHP?, instead you can use mysqli_* or PDO

I think that it is a very bad design to store genre like you do it
How you will update your data ?
How to retrieve movies by genre ?

Each simple SQL operation will be a nightmare, instead of this, spend your time to correct your desgin, for example you can simply create a dedicated table from genre

ID | type
------------
1  | Comedy
2  | Horror
3  | Mangas
4  | ... 
5  | Animation

And create an Entity Table that will associate the movie with [1, N] genre

MovieId | GenreId
-----------------
2       | 1
2       | 2
2       | 5
Community
  • 1
  • 1
Halayem Anis
  • 7,654
  • 2
  • 25
  • 45
3

Try using PHP's explode() function. This function expects 2 parameters, a delimiter, and a string. The delimiter should be what you want to look for in the string to separate items. In practice this would look like:

$genreArray = explode(' ', $row->genre);

Now $genreArray will look something like this (output generated from var_dump($genreArray)):

array(3) { [0]=> string(9) "Animation" [1]=> string(6) "Comedy" [2]=> string(6) "Horror" }
Mike Hamilton
  • 1,519
  • 16
  • 24
-1

Try this

  1. Through multiple arrays:

    <?
    $sql = "SELECT moviename,genre FROM movieHosting";
    $query = mysql_query($sql);
    $row = mysql_fetch_array($query);
    /* fetched value */
    $moviename = $row['moviename'];
    $genre= $row['genre'];
    ?>
    
  2. Through single arrays to produce result like $genreArray = array("Animation","Comedy","Horror");

    <?
    $sql = "SELECT moviename,genre FROM movieHosting";
    $query = mysql_query($sql);
    $row = mysql_fetch_array($query);
    /* fetched value */
    $array =array();
    foreach($row as $r){
        $moviename = $r['moviename'];
        $genre = $r['genre'];
        $array_push = array_push($array,$moviename,$genre);
        print_r($array_push);
    }
    ?>
    
Ronin
  • 1,688
  • 1
  • 13
  • 23
codegeek
  • 230
  • 1
  • 3
  • 12
-2
$genreArray = preg_split("/[\s,]+/", "Animation Comedy Horror");
print_r($genreArray );

The output:

Array
(
    [0] => Animation
    [1] => Comedy
    [2] => Horror
)
gofr1
  • 15,741
  • 11
  • 42
  • 52
  • looks about what I need quick question would this work in the syntax –  Mar 08 '16 at 01:24
  • $genreArray = preg_split("/[\s,]+/", $row->genre); and would it actually store an array inside $genreArray –  Mar 08 '16 at 01:25
  • Yes it would actually store an array. I especially show you example of what you get by using this function. It will split the phrase by any number of commas or space characters, which include " ", \r, \t, \n and \f – gofr1 Mar 08 '16 at 05:51
  • What's the benefit of using a more expensive regular expression with preg_split() compared to the explode() function? They both do the same in this instance, but explode() is quicker. – Chief Wiggum Mar 08 '16 at 06:55
  • In the PHP manual notes section here [link](http://us3.php.net/manual/en/function.preg-split.php) they say: **Tip** If you don't need the power of regular expressions, you can choose **faster** (albeit simpler) alternatives like `explode()` or `str_split()`. – Chief Wiggum Mar 08 '16 at 07:03
  • As I wrote this code helps you to avoid some special characters in incoming string. In this particular sample of data to split in array you will not see any changes in productivity or speed. – gofr1 Mar 08 '16 at 07:18
  • I have bad experience using str_split, when once our data providers change an output of there api, and add "," as separator... :) – gofr1 Mar 08 '16 at 07:25