0

I have a list of names and each name consist of 2-4 words: name, (if exist) middle name(s), surname.

These are the names:

  • Ali Yilmaz
  • Taha Ugur Unal
  • Omer Ibrahim Tahsin Son
  • Recai Sahin

etc.

I want to print this names as this: Surname, name middle name(s) (if exist)

The names above will be:

  • Ali Yilmaz -> Yilmaz, Ali
  • Taha Ugur Unal -> Unal, Taha Ugur
  • Omer Ibrahim Tahsin Son -> Son, Omer Ibrahim Tahsin
  • Recai Sahin -> Sahin, Recai

etc.

If I had only one name I can use that code:

    <?php $exp1 = explode(" ", $author1); ?>        
    <?php if (count($exp1) == 2) {?>
    <?php print ($exp1[1] .', ' .$exp1[0]); ?>

    <?php } elseif (count($exp1) == 3) {?>
    <?php print ($exp1[2] .', ' .$exp1[0] .' ' .$exp1[1]); ?>

    <?php } elseif (count($exp1) == 4) {?>
    <?php print ($exp1[3] .', ' .$exp1[0] .' ' .$exp1[1] .' ' .$exp1[2]); ?>        

    <?php }?>


Each page can have different numbers of author and I thought I could use foreach to apply the above code for each author name but I couldn't do this.

I tried a piece of code such that:

        <?php foreach $author as $obj): ?>
            <?php $a = explode (" ", $obj) ?> 
        <?php endforeach ?>
        ...


But it gives error:

explode() expects parameter 2 to be string, array given.

How can I do this?

9
  • why you close your php each line? Commented Nov 22, 2014 at 12:28
  • Please do a var_dump of $obj) immediately within the outer foreach and post the results so we can investigate. Commented Nov 22, 2014 at 12:29
  • @vp_arth because it's about Drupal structure (drupal.org/coding-standards). Commented Nov 22, 2014 at 12:31
  • @Dai, this the results: Array array(2) { ["tid"]=> string(4) "5930" ["taxonomy_term"]=> object(stdClass)#117 (8) { ["tid"]=> string(4) "5930" ["vid"]=> string(1) "2" ["name"]=> string(22) "Çiğdem Apaydın Kaya" ["description"]=> NULL ["format"]=> NULL ["weight"]=> string(1) "0" ["vocabulary_machine_name"]=> string(5) "yazar" ["rdf_mapping"]=> array(5) { ["rdftype"]=> array(1) { [0]=> string(12) "skos:Concept" } ["name"]=> array(1) { ["predicates"]=> array(2) { [0]=> string(10) "rdfs:label" [1]=> string(14) "skos:prefLabel" } } ["description"]=> array(1) { ["predicates"]=> array(1) { ... Commented Nov 22, 2014 at 12:36
  • This Coding Standards never say to do this) Commented Nov 22, 2014 at 12:36

4 Answers 4

2
<?php
$names = array(
  'Ali Yilmaz',
  'Taha Ugur Unal',
  'Omer Ibrahim Tahsin Son',
  'Recai Sahin'

);

// First you should iterate through:
foreach ($names as $name) {
  // and now, let make the job
  // split by words
  $parts = explode(' ', $name);
  if (count($parts) == 1) {
    echo "{$name}<br/>";
    continue;
  }
  // get last word
  $last = array_pop($parts);
  // Print last one, comma, and rest of name
  echo "{$last}, " . implode(' ', $parts) . "<br/>";
}
Sign up to request clarification or add additional context in comments.

3 Comments

@RajibGhosh, no, error-free code not exists at all :)
and good job @vp_arth...i am trying to updated your code ...if you have any problem i can remove my updated code ...if you want. i am open..and now i think your code is ok.
I've not any problem) it is not a contest
1

If you had a single string, you would

  • split all the words with explode().
  • take out the surname and store it.
  • join the rest of the name with implode().

See the example below:

<?php

$name = "Son of the Mask";
$words = explode(" ", $name);  // split the string wherever there is a whitespace.
$surname = array_pop($words);
$restOfTheName = implode(" ", $words);  // join the words with a whitespace in between them.

echo $surname . ", " . $restOfTheName;

?>

On the other hand, if you have a list of names in an array called, say, $namelist, you can use the foreach() loop to iterate through the list.

You would do something like:

<?php

foreach ($namelist as $name)
{
    $words = explode(" ", $name);
    $surname = array_pop($words);
    $restOfTheName = implode(" ", $words);

    echo $surname . ", " . $restOfTheName;
}

?>

Hope that helped :-)


EDIT:

And no, you need not use <?php and ?> on every line. This is only helpful, say when you want to use small snippets of PHP inside your HTML tags.

For example, let us say you want to display some information in an unordered list. Then you would do something like

<?php

$info1 = "Head over to Google.com";
$info2 = "Search before you post!";

?>

<ul>
    <li><?php echo $info1; ?></li>
    <li><?php echo $info2; ?></li>
</ul>

But, doing this for a script that contains only PHP code doesn't make sense. Moreover, it renders your code difficult to read, and eats up a lot of your valuable time.

1 Comment

Thanks, it's working. And for your edit, you're right; I'm using some span tags and so I'm using <?php and ?> on every line. As you said I don't need to use for each line, maybe for some of them. Thanks again.
0

you can try this

   <?php
     $newNameArray=array();
     $namesArray = array(
       'Ali Yilmaz',
       'Taha Ugur Unal',
       'Omer Ibrahim Tahsin Son',
       'Recai Sahin'
     );
    foreach ($namesArray as $name) {

         $partsOfName = explode(" ", $name);
        //last name
        $lastName = array_pop($partsOfName);
        // store the name in new array
       $newNameArray[]=$lastName.", ".implode(" ", $partsOfName);
     }

    //show all names 
    var_dump($newNameArray);
?>

you can see this for details explode and array push

Comments

-1

use this

foreach ($author as $obj) {
    $nameArr = explode(' ',$obj);
    if(count($nameArr) > 1) {
        $lname = $nameArr[count($nameArr)-1];
        array_pop($nameArr);
        echo $lname.", ".implode(' ',$nameArr);
        echo "<br />";
    } else {
        echo $obj;
        echo "<br />";
    }
}

Comments

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.